I need to use scanner to get 2 inputs. 1st input is a sequence of integers that I need to store in ArrayList. 2nd input should go right after the first one and it's integer as well. My question is - how do I stop accepting input for ArrayList and tell the machine to ask for a second number. I ended with something like this but it does not of course work because it just keeps asking for integers for arraylist. And yes, I need to use ArrayList for the task, since I don't know how many integers there will be. I also haven't learned List interface yet so I need to use what I have in my disposal.
while (scanner.hasNextInt()) {
numbers.add(scanner.nextLine());
if (scanner.hasNextInt()) {
referenceNumber = scanner.nextInt();
}
}
CodePudding user response:
I managed to solve it this way, though probably not optimal
String inputString = scanner.nextLine();
String[] inputArray = inputString.split(" ");
int[] numberArray = new int[inputArray.length];
for (int i = 0; i < inputArray.length; i ) {
numberArray[i] = Integer.parseInt(inputArray[i]);
}
if (scanner.hasNextInt()) {
referenceNumber = scanner.nextInt();
}
CodePudding user response:
if your input sequence is something like 23 34 54 46 then you can use this
Scanner scanner = new Scanner(System.in);
String integers = scanner.nextLine();
StringTokenizer string = new StringTokenizer(integers);
ArrayList<Integer> list = new ArrayList<Integer>();
while(string.hasNextToken()){
list.add(Integer.parseInt(string.nextToken()));
}