繁体   English   中英

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

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

我需要能够在控制台中输入随机数的整数,然后在完成后输入一个特殊字符,例如 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++;
}

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

这里是 go:

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+仅允许数字,即仅 integer 数字。
  3. break导致循环中断。

如有任何疑问/问题,请随时发表评论。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM