2016-03-02 93 views
1
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号和实施例可以是,停止键盘输入?

条目:

2 3(输入)读2号和总结

1 2 (输入)读2号和总结

(进入),并在这里结束循环因为进入并没有数字并给出了解决方案

退出:

我不知道我UF

+0

将'u'值打印到while循环中并观察它在按ENTER时的状态。因此设置如果和里面如果休息,这将为你工作。 –

回答

0

阅读整行的前贴好,自己解析它。如果该行为空,则退出循环结束程序。如果不为空,则将该行传递给新的扫描仪。

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); 
} 
+0

非常感谢你! – limit2001