'How to solve looping of multiple-line reading while breaking Scanner in Java?
Im trying to read multiple lines from console. I don't know the number of lines and it may differ. I know only that each line contains 2 numbers and space between them. But when I try to read them, scanner always expects a new line after I break it. I tried using .hasNextLine() and if (line.isEmpty()) conditions and other variants that I had found, but always had the same result. Part of code:
Scanner s = new Scanner(System.in);
HashMap<Integer, Integer> numberPairs = new HashMap<>();
String line;
while(s.hasNextLine()) {
line = s.nextLine();
if (line.isEmpty()) {
break;
} else {
int[] numbers = parseLine(line);
if (numbers != null) {
numberPairs.put(numbers[0], numbers[1]);
}
}
}
Though, it was working when code was looking this way (but it was processing only second line from 2 lines I had entered):
Scanner s = new Scanner(System.in);
HashMap<Integer, Integer> numberPairs = new HashMap<>();
while(s.hasNextLine()) {
if (s.nextLine().isEmpty()) {
break;
} else {
int[] numbers = parseLine(s.nextLine());
if (numbers != null) {
numberPairs.put(numbers[0], numbers[1]);
}
}
}
Where could be the issue and how to solve it?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
