I am having troubles with java. I need to scan numbers (example: 1 3 4 2 5 6 7
) and put them into array. The problem is I don't know how long it will be. Is there a command that I can use to determine the length of the numbers putted in scanner?
But we can take array input by using the method of the Scanner class. To take input of an array, we must ask the user about the length of the array. After that, we use a Java for loop to take the input from the user and the same for loop is also used for retrieving the elements from the array.
Accessing 2D Array Elements In Java, when accessing the element from a 2D array using arr[first][second] , the first index can be thought of as the desired row, and the second index is used for the desired column. Just like 1D arrays, 2D arrays are indexed starting at 0 .
nextInt() The nextInt() method of a Scanner object reads in a string of digits (characters) and converts them into an int type. The Scanner object reads the characters one by one until it has collected those that are used for one integer. Then it converts them into a 32-bit numeric value.
You can use List. removeAll() method to filter an array.
If you don't want to use ArrayList, as a workaround, I advice to read the entire line and then split to get the length and individual values:
String line = scanner.nextLine();
String[] values = line.split(" ");
int[] intValues = new int[values.length];
int indx = 0;
for(String value:values){
intValues[indx++] = Integer.parseInt(value);
}
EDIT: Second approach:
List<Integer> numList = new ArrayList<Integer>();
int number = 0;
while (number != -1) {
System.out.println("Enter a positive integer value (or -1 to stop): ");
number = Integer.parseInt(in.nextLine());
if (number != -1){
numList.add(number);
}
}
in.close();
Integer[] numArray = numList.toArray(new Integer[numList.size()]);
EDIT2: Taking care of multiple numbers in the same line and terminating at empty line
List<Integer> numList = new ArrayList<Integer>();
while(true) {
System.out.println("Enter a positive integer value (or -1 to stop): ");
String line = in.nextLine();
if(line.length() <1){
break;
}
String [] numbers = line.split(" ");
for(String num: numbers){
numList.add(Integer.parseInt(num));
}
}
in.close();
Integer[] numArray = numList.toArray(new Integer[numList.size()]);
Use an ArrayList if you want a variable-size collection.
ArrayList<Integer> lst = new ArrayList<Integer>();
lst.add(scanner.getInt());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With