首页 > 解决方案 > 如果用户输入特定关键字,如何停止从扫描仪读取?

问题描述

我需要能够在控制台中输入随机数的整数,然后在完成后输入一个特殊字符,例如 Q。但是,我不确定如何验证输入是否为 int。

关键是用户输入 x 数量的整数,这些整数从客户端发送到服务器,服务器从一个简单的方程返回结果。我计划一次发送一个,因为它可以输入任意数量的整数。

我尝试了几种不同的方法。我尝试过使用 hasNextInt。我尝试了 nextLine 然后将每个输入添加到 ArrayList 然后解析输入。

List<String> list = new ArrayList<>();
String line;

while (!(line = scanner.nextLine()).equals("Q")) {
    list.add(line);
}

list.forEach(s -> os.write(parseInt(s)));

这是我最初验证输入的另一个循环,但我不确定完成后如何退出循环。

while (x < 4) {
    System.out.print("Enter a value: ");

    while (!scanner.hasNextInt()) {    
        System.out.print("Invalid input: Integer Required (Try again):");
    }

    os.write(scanner.nextInt());
    x++;
}

任何帮助,将不胜感激。谢谢

标签: javajava.util.scanner

解决方案


干得好:

Scanner scanner = new Scanner(System.in);
List<Integer> list = new ArrayList<Integer>();

while (scanner.hasNext()) {
    String line = scanner.nextLine();

    if (line.equals("Q")) {
        scanner.close();
        break;
    }

    try {
        int val = Integer.parseInt(line);
        list.add(val);
    } catch (NumberFormatException e) {
        System.err.println("Please enter a number or Q to exit.");
    }
}

推荐阅读