Scanner s = new Scanner(System.in);
List<Integer> solutions = new LinkedList<>();
int o = 0;
while (o != 10) { // I want to read 2 numbers from keyboard
int p = s.nextInt(); // until send and enter, this is where is my
int c = s.nextInt(); //doubt
int d = p + c;
solutions.add(d);
o = System.in.read();
}
Iterator<Integer> solution = solutions.iterator();
while (solution.hasNext()) {
int u = solution.next();
System.out.println(u);
}
我遇到的问题是,如何发送 Enter 来结束循环?因为如果我输入另外 2 个数字,则 System.in.read() 会获取第一个数字,示例可能是,
条目:
2 3(输入)读取2个数字并求和
1 2(输入)读取2个数字并求和
(输入)这里结束循环,因为输入并且没有数字,并给出了解决方案
退出:
5
3
我不知道我之前发过帖子
最佳答案
读整行并自己解析。如果该行为空,则退出循环并结束程序。如果它不为空,则将该行传递给新的扫描仪。
List<Integer> solutions = new LinkedList<>();
Scanner systemScanner = new Scanner(System.in);
String line = null;
while ((line = systemScanner.nextLine()) != null && !line.isEmpty()) {
Scanner lineScanner = new Scanner(line);
int p = lineScanner.nextInt();
int c = lineScanner.nextInt();
int d = p + c;
solutions.add(d);
}
Iterator<Integer> solution = solutions.iterator();
while (solution.hasNext()) {
int u = solution.next();
System.out.println(u);
}
关于java - 停止键盘输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35748445/