停止键盘输入?

时间:2016-03-02 13:21:32

标签: java keyboard

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个数字和总和

(输入)并且这里因为输入而没有数字而结束循环并给出了解决方案

出口:

5

3

我不知道,如果我在

之前发布得很好

1 个答案:

答案 0 :(得分: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);
}