【问题标题】:Stop keyboard enter? [duplicate]停止键盘输入? [复制]
【发布时间】:2016-06-15 09:04:37
【问题描述】:
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);
}

我遇到的问题是,我如何发送一个输入以结束循环?因为如果我输入另外 2 个数字,System.in.read() 将采用第一个数字,例如,

条目:

2 3(输入)读取 2 个数字并求和

1 2(输入)读取 2 个数字并求和

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

退出:

5

3

我不知道我之前发过的好不好

【问题讨论】:

  • 将 'u' 值打印到 while 循环中,并在按下 ENTER 时观察它是什么。相应地设置 if 和 inside if break,这对你有用。

标签: java keyboard


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-28
    • 1970-01-01
    • 2012-02-04
    • 1970-01-01
    • 2017-04-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多