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);
}
我的问题是,如何发送回车以结束循环?因为如果我再输入两个数字,则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);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句