如果用户输入特定关键字,如何停止从扫描仪读取?

How to stop reading from a scanner if the user inputs a specific keyword?

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

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

我尝试了几种不同的方法。我试过使用 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++;
}

如有任何帮助,我们将不胜感激。谢谢

给你:

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

按如下操作:

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        List<Integer> list = new ArrayList<Integer>();
        String input = "";
        while (true) {
            System.out.print("Enter an integer (Q to quit): ");
            input = in.nextLine();
            if (input.equalsIgnoreCase("Q")) {
                break;
            }
            if (!input.matches("\d+")) {
                System.out.println("This is an invalid entry. Please try again");
            } else {
                list.add(Integer.parseInt(input));
            }
        }
        System.out.println(list);
    }
}

样本运行:

Enter an integer (Q to quit): a
This is an invalid entry. Please try again
Enter an integer (Q to quit): 10
Enter an integer (Q to quit): b
This is an invalid entry. Please try again
Enter an integer (Q to quit): 20
Enter an integer (Q to quit): 10.5
This is an invalid entry. Please try again
Enter an integer (Q to quit): 30
Enter an integer (Q to quit): q
[10, 20, 30]

备注:

  1. while(true) 创建一个无限循环。
  2. \d+ 只允许数字,即只允许整数。
  3. break 导致循环中断。