In the program I'm working on, I created a loop to receive 20 individual characters as user input, convert to char, store in array2, and return array2 to main. When I ran the program I wrote, it seems that the code I wrote didn't store the chars in array2 properly.
In main:
// Create array to hold user's answers, and pass answers to the array.
char array2[ ] = new char[20];
getAnswers(array2);
In getAnswers():
// getAnswers method requests user input and passes to array2.
public static char[ ] getAnswers(char array2[ ])
{
String input; // Holds user input.
Scanner keyboard = new Scanner(System.in);
// Request user input.
System.out.println("Enter the answers for the the multiple choice exam.");
// Loop to receive input into array.
for (int index = 0; index < 20; index++)
{
System.out.print("Enter number " + (index + 1) +": ");
input = keyboard.nextLine();
array2 = input.toCharArray();
}
return array2;
}
try
array2[index] = input.charAt(0);
after you obtain the value into the input variable instead of assigning it a new char array every time through the loop.
Right now you're creating a new array2 with each input and thereby destroying any previous input with the previous array2 that you created.
If you absolutely need to create a char array, why not append the String answers into a StringBuffer object, and then when done, call toString().toCharArray() on the StringBuffer.
Myself, I'd create an ArrayList and just append the response to the ArrayList and at the end return the ArrayList.
It is not good idea to modify the method param. You can try :
public static char[ ] getAnswers(char array2[ ])
{
String input; // Holds user input.
Scanner keyboard = new Scanner(System.in);
// Request user input.
System.out.println("Enter the answers for the the multiple choice exam.");
String tmp = "";
for (int index = 0; index < 20; index++)
{
System.out.print("Enter number " + (index + 1) +": ");
input = keyboard.nextLine();
tmp += input.chaAt(0); // check length is > 0 here
}
return tmp.toCharArray();
}
Related
I am trying to have the user set the name for how many numbers they set. for example if they set 3 the program asks for name 3 times and then sets those names to a different varible inside an array.
public static void main(String[] args) {
Scanner Num = new Scanner(System.in);
Scanner Name = new Scanner(System.in);
System.out.println("How many names do you want to enter: ");
int number = Num.nextInt();
int[] numbs = new int[number];
for (int i = 0; i < numbs.length; i++) {
System.out.println("What is your name");
String [] nameArray = Name.nextLine();
Just a small improvement over Titan's answer.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("How many names do you want to enter: ");
int numberOfTimes = sc.nextInt();
String[] names = new String[numberOfTimes];
sc.nextLine();
for (int i = 0; i < numberOfTimes; i++) {
System.out.println("What is your name");
names[i] = sc.nextLine();
}
System.out.println(Arrays.toString(names));
}
Starting point
Here are several things happening in your posted code:
You have two different Scanners, each reading from System.in
After prompting for user input (int number = Num.nextInt()), you're using that number to create an array of size "number"
When you call nextLine(), you are assigning the result to a string array (String []).
Working solution
Here's a variation which addresses those issues, with a few additions, too:
Use one Scanner, and give it a general name ("scanner", not "Num") since a scanner has nothing to do with one specific data type. Any scanner can read strings, integers, booleans, bytes, etc. Look in Javadoc for the full set of supported data types.
Check if user input is valid before trying to create an array – if user enters "-1" that's a valid integer value, but not valid for allocating an array – new int[-1]) would throw a java.lang.NegativeArraySizeException at runtime.
Use "next()" instead of "nextLine()" – with the rest of your example, using "nextLine()" results in skipping one line without direct interaction from the user (so the first "name" is always an empty string)
Assign the result of "next()" to a String (not String[]), matching the return type from the method
Use "System.out.print()" instead of "println()", a little tidier program output
Use lowercase names to follow Java naming conventions ("scanner", not "Scanner")
Scanner scanner = new Scanner(System.in);
System.out.print("How many names do you want to enter: ");
int times = scanner.nextInt();
if (times < 0) {
System.out.println("negative numbers not allowed");
} else {
String[] names = new String[times];
for (int i = 0; i < times; i++) {
System.out.print("What is your name: ");
names[i] = scanner.next();
}
System.out.println(Arrays.toString(names));
}
And here's a sample run:
How many names do you want to enter: 3
What is your name: one
What is your name: two
What is your name: three
[one, two, three]
Create a String array of number length outside the loop and initialize each index with name as input.
By the way you only need to create one Scanner object for input(Not needed to create various objects for different input).
Edit - There was no use of numbs array.
Scanner sc=new Scanner(System.in);
System.out.println("How many names do you want to enter: ");
int number = sc.nextInt();
String []nameArray=new String[number];
/*Since nextInt() does not read the newline character in your input
created by hitting "Enter"*/.
sc.nextLine();
for (int i = 0; i < number; i++) {
System.out.println("What is your name");
nameArray[i]=sc.nextLine();
}
sc.close(); //To prevent memory leak
I am trying some algorithm which requires large no of input samples for testing but at a time I cannot take input more than certain number of times.
N = sc.nextInt();
...
int[] arr = new int[N];
for(int i=0; i<N; i++){
arr[i] = sc.nextInt();
}
for(int elem: arr){
System.out.println(elem+" ");
}
Input format is
N
//HERE GOES ARRAY ELEMENTS
where N- no of element in array
I'm using this user input test_case_1, but I can only input fraction of the given values.
I wanted to know what is restricting the number of input in vscode
Usually, using a scanner is perfectly alright. But with input samples of up to 90 000, which seems to be test case 1, it might be very slow due to excessive flushing.
Something like this might be more effective:
BufferedReader br = new BufferedReader(new FileReader("temp_code_input.txt"));
...
int N = Integer.parseInt(br.readLine());
...
StringTokenizer st = new StringTokenizer(br.readLine());
/*
Assumes every input is on the same line. If not, create a new StingTokenizer
for each new line of input.
*/
int[] arr = new int[N];
for (int i = 0; i < N; i++) {
arr[i] = Integer.parseInt(st.nextToken());
}
for (int elem : arr) {
System.out.println(elem)
}
I'm just manually inputting the values by pasting it
It would be easier for you to just read this input from a file with the Scanner class.
String s = Files.readString("PATH_TO_YOUR_FILE", StandardCharsets.US_ASCII);
// create a new scanner with the specified String Object
Scanner scanner = new Scanner(s);
// find the next int token and print it
// loop for the whole scanner
while (scanner.hasNext()) {
// if the next is a int, print found and the int
if (scanner.hasNextInt()) {
//Store the data here ...
}
// if no int is found, print "Not Found:" and the token
System.out.println("Not Found :" + scanner.next());
}
When i test the input you provided, it stops and not accept more numbers when i paste them, so i ask in github: Limit max number of terminal input then get the reply:
when I paste your example input into the terminal, it succeeds
(although takes quite awhile) - what you might be seeing is the output
(pasted text) trimmed relative to what you're expecting because of the
maximum terminal scrollback which can be configured with
terminal.integrated.scrollback
So please waiting because it would succeed that pasting the input. Enlarge the value of terminal.integrated.scrollback in Settings.json to check the output.
I'm trying to create a program that takes the user's input and then scans the user's input into an array with a for loop. That way I can loop through the array to find if the string is a word palindrome or not. A word palindrome differs from a palindrome in that it is the whole word in reverse rather than each individual letter in reverse. When the program that I wrote prints it just prints null, which I believe means that it's not storing what the scanner scanned.
Below is what I've written:
String userInput, scannedWord;
Scanner keyboard = new Scanner(System.in); //scanner for user input
System.out.print("Please enter a sentence: ");
userInput = keyboard.nextLine(); //stores user input
Scanner stringScan = new Scanner(userInput); //scanner to scan through user input
int userInputLength = userInput.length(); //to find word count
int wordCount = 0; //for array size
for (int i = 0; i < userInputLength; i++) //finds word count
{
while(stringScan.hasNext())
{
scannedWord = stringScan.next();
wordCount = wordCount + 1;
}
}
String stringArray[] = new String[wordCount];
for (int i = 0; i < userInputLength; i++) //should store scanned words into the array
{
while (stringScan.hasNext())
{
scannedWord = stringScan.next();
stringArray[i] = scannedWord;
}
}
System.out.println(Arrays.toString(stringArray)); //how I've checked if it's storing
You've got some funky logic going on here. A few things:
userInput = keyboard.nextLine(); //stores user input
int userInputLength = userInput.length(); //to find word count
userInputLength is the length of the userInput string, which is the number of characters in the string, not the number of words.
It looks like the while loop is used simply to calculate the required size of the array, but the outer for loop is not required. You're effectively saying, for every character in the input string, while the scanner has another word, count the word, which doesn't make much sense.
You do something similar in your second for loop, which also doesn't make much sense.
for (int i = 0; i < userInputLength; i++) //finds word count
{
while(stringScan.hasNext())
{
scannedWord = stringScan.next();
wordCount = wordCount + 1;
}
}
It would be easier to use a List and save yourself the trouble that comes with fixed size arrays. You can just initialize the list and add things to it without caring about how big it is.
List<String> words = new ArrayList<String>();
words.add(word1);
words.add(word2);
Here's some code to simplify your problem a little:
Scanner keyboard = new Scanner(System.in); //scanner for user input
System.out.print("Please enter a sentence: ");
String userInput = keyboard.nextLine(); //stores user input
Scanner stringScan = new Scanner(userInput); //scanner to scan through user input
List<String> words = new ArrayList<String>();
while (stringScan.hasNext())
{
String scannedWord = stringScan.next();
words.add(scannedWord);
}
System.out.print(Arrays.toString(words.toArray())); // nasty! but you can see what's in the array for debugging
I know this isn't something you are supposed to do yet but I'm still trying to figure out a way to run this loop, an letting the arr[i] inside it "know" about the rise of the number of elements in the array (which I declare outside of the loop because I don't want it to make a new one each time).
int counter=1, note=0;
System.out.println("Please enter characters, -1 to stop: ");
do {
char[] arr= new char[counter];
for (int i=0;i<=counter;i++){
arr[i] = s.next().charAt(0);
if (arr[i]==-1){
note = -1;
break;
}
++counter;
}
} while (note>=0);
From your much clearer comment, this is an example main method.
public static void main(String[] args) {
Scanner input = new Scanner(System.in); // Input
int amt = 0; // Amount of chars received
List<Character> chars = new ArrayList<>(); // ArrayList is easier for now
while (input.hasNext()) { // Grabs Strings separated by whitespaces
String token = input.next(); // Grab token
if (token.equals("-1")) {
break; // End if -1 is received
} else if (token.length() != 1) {
throw new IllegalArgumentException("Token not one char: " + token);
// It seems you want only chars - this handles wrong input
} else {
chars.add(token.charAt(0)); // Adds the character to the list
amt++; // Increment amt
}
}
char[] array = new char[amt]; // Converting to an array
for (int i = 0; i < amt; i++) {
array[i] = chars.get(i); // Copies chars into array
}
System.out.println(Arrays.toString(array)); // Handle data here
}
I hope that this is correct. An input of a b c d -1 leads to an output of [a, b, c, d].
If you use the Input String size check I think as you will be resolved.
int counter=0, note=0;
System.out.println("Please enter characters, -1 to stop: ");
String input=s.nextLine();
counter=input.length();
char[] arr= new char[counter];
for (int i=0;i<counter;i++){
arr[i] = input.charAt(i);
}
and If you are using the ArrayList rather than Array is no need to worry about the size.
ArrayList is effective flexable data
cause using add function.
Details of my Homework
Topic: Single Dimensional Array
Write a java program that first read in the size of a one dimensional array, read in each array element of double type, reverses the order of this one-dimensional array.
Do not create another array to hold the result.
Hint: Use the code in the text for exchanging two elements.
Sample Output:
Please input the size of array: 4
Please input 4 double numbers: 1.0, 2.0, 3.0, 4.0
After reverse order: 4.0, 3.0, 2.0, 1.0
I have 2 problems with my assignment. Wondering if anyone can help me find a solution.
I need to fill the values of an array (double[] myArray) using
Scanner input from a single line for multiple doubles.
I need to reverse the order of the values inside the array WITHOUT
using a 2nd array.
This is my code so far.
Scanner sc = new Scanner(System.in);
System.out.println("Please input the size of array: ");
int arraySize = sc.nextInt(); //Stores user input
double[] myArray = new double[arraySize]; //Create array[userInput]
System.out.print("Please input " + arraySize + " double numbers: ");//Collect user input
int j = 0;
while (sc.hasNext()) { //Another Failed Attempt to collect the input from a single line
if (sc.hasNextDouble()) {
myArray[j] = sc.nextDouble(); //Insert user input into array
j++;
}
}
Collections.reverse(Arrays.asList(myArray));//Doesn't work :(
System.out.println("After reverse order: ");
for (int i=0;i<arraySize;i++)
System.out.println(myArray[i]);
My problem is that when the input for the doubles is given by the user the console moves to the next line still expecting input, if input is given ArrayIndexOutOfBounds is thrown
You misunderstood something here.
In Collections.reverse(Arrays.asList(myArray)); you use Arrays.asList(myArray) that is returning a new List. Afterwards you reverse it, but you don't assign it to a variable and you just lose it.
That's not how you need to do it.
You need to think of another way of doing it.
I'll give you a hint: use the hint in the question!
and if you say you just need to reverse it, why do you need to sort it?!
I need to fill the values of an array (double[] myArray) using
Scanner input from a single line for multiple doubles.
If I understand this correctly first you need to read entire line and then parse it to read all double values from it. To read entire line of doubles from user you can invoke nextLine from scanner which handles System.in stream. Then you can either
split line on spaces and use Double.parseDouble(String) (to get double from String) on each String element from result array
wrap this line with another Scanner and use its nextDouble.
BTW if you want to read next line after nextDouble (or nextInt or nextAnythingExceptLine) you need to consume reminded line separators with another nextLine method (more info here Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods).
So first part of your assignment can look like
Scanner sc = new Scanner(System.in);
System.out.println("Please input the size of array: ");
int arraySize = sc.nextInt();
sc.nextLine();//consume line separator to let `nextLine` read actuall next line
double[] myArray = new double[arraySize];
System.out.print("Please input " + arraySize
+ " double numbers in one line: ");
String line = sc.nextLine();
System.out.println("your numbers are "+line);
Scanner lineScanner = new Scanner(line);
int j = 0;
while (lineScanner.hasNextDouble()) {
myArray[j++] = lineScanner.nextDouble();
}
lineScanner.close();
Your second problem is that generics don't support primitive types so T in asList(T..) can be only object type. Unfortunately autoboxing works only on primitive types, so double[] can't be promoted to Double[] because every array is already an object (even arrays of primitive types).
This means that result of Arrays.asList(T.. data) for argument myArray of type double[] will not return List<double> or List<Double> but List<double[]> — a list which holds one object, the passed array, not the elements of this array. That is why reversing doesn't work for you (reversing list containing one element changes nothing, as you can't reorder list with only one element).
To solve this problem simply change type of myArray form double[] (array of primitive types) to Double[] (array of object types), to let generic type T from asList(T..) represent non-primitive Double (otherwise T can only be inferred as non-primitive double[] type).
So change your line
double[] myArray = new double[arraySize]; // Create array[userInput]
to
Double[] myArray = new Double[arraySize]; // Create array[userInput]
Probably you have to instantiate a new Scanner after you have read the array size.
Scanner sc = new Scanner(System.in);
System.out.println("Please input the size of array: ");
int arraySize = sc.nextInt(); //Stores user input
double[] myArray = new double[arraySize]; //Create array[userInput]
sc.close();
sc = new Scanner(System.in).useDelimiter(",");
System.out.print("Please input " + arraySize + " double numbers: ");//Collect user input
int j = 0;
Collections.reverse(Arrays.asList(myArray));//Doesn't work :(
First of all: Arrays.asList get Object varargs and if you pass primitive array you'll get list of primitive arrays.
Second moment: Arrays.asList returns list. And if you changed it list your original array(from which you create list) will not be changed.
You shall make collection instead array and reverse it.
For example:
Scanner sc = new Scanner(System.in);
System.out.println("Please input the size of array: ");
int arraySize = sc.nextInt(); //Stores user input
System.out.print("Please input " + arraySize + " double numbers: ");//Collect user input
List<Double> myList = new ArrayList<Double>();
for (int i = 0; i < arraySize;) {
if (sc.hasNextDouble()) {
myList.add(sc.nextDouble());
i++;
}
}
Collections.reverse(myList);//Doesn't work :(
System.out.println("After reverse order: ");
for (int i=0;i<arraySize;i++)
System.out.println(myList.get(i));
Use this to reverse your array.
You need to get half of the array's length to get the full reverse of the array
for(double i = 0; i < Array.length / 2; i++)
{
int x = Array[i];
Array[i] = Array[Array.length - i - 1];
Array[Array.length - i - 1] = x;
}
package display.pkg1;
import java.util.Scanner;
public class Display1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println(" Enter the size of array ");
int size = input.nextInt();
System.out.println(" Enter array Elements ");
double []lol = new double [size];
for(int i =0 ; i<size ; i++)
{
lol[i] = input.nextDouble();
}
for(int i =size-1 ; i>=0 ; i--)
{
System.out.println(" Array element " + ( i +1) + " is " + lol[i]);
}
}
}
Try this code
import java.util.Scanner;
public class ReverseArray{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please input the size of array: ");
int arraySize = sc.nextInt(); //Stores user input
double[] myArray = new double[arraySize]; //Create array[userInput]
System.out.print("Please input " + arraySize + " double numbers: ");//Collect user input
for(int i = 0; i < myArray.length; i++){
if (sc.hasNextDouble()) {
myArray[i] = sc.nextDouble(); //Insert user input into array
}
}
// Reverse myArray
for(int i = 0, j = myArray.length-1; i < (myArray.length/2); i++, j--){
Double temp = myArray[i];
myArray[i] = myArray[j];
myArray[j] = temp;
}
//Print the reversed myArray
System.out.println("After reverse order: ");
for (int i=0;i<arraySize;i++)
System.out.println(myArray[i]);
}
}