问题
I'm simply trying to read integers (separated by spaces, such as : "6 9 20") from the console and transferring them into an array for later use. However, with the code I currently have written, my scanner object never stops reading my input. I feel like the scanner object simply doesn't know exactly when to stop taking input, but I'd like it to stop reading as soon as I hit Enter. I've searched this website extensively for a precise answer, but to no avail.
Here is my code:
int[] mcNug = new int[5];
Scanner scanner = new Scanner(System.in);
List list = new ArrayList<Integer>();
int i = 0;
while(scanner.hasNextInt() && scanner.hasNext())
{
list.add(scanner.nextInt());
mcNug[i] = (int) list.get(i);
i++;
scanner.next();
}
回答1:
use a nextLine()
.
while( scanner.hasNextLine() ){
String line = scanner.nextLine();
String[] numbers = line.split("\\s+");
... do something with numbers array ..
}
来源:https://stackoverflow.com/questions/21211634/scanner-never-stops-reading-input