java - 将扫描仪与整数序列一起使用

标签 java java.util.scanner

我正在编写一个程序来从控制台获取一系列整数,例如

1 5 3 4 5 5 5 4 3 2 5 5 5 3

then compute the number of occurrences and print the following output:

0 - 0
1 - 1
2 - 1
3 - 3
4 - 2
5 - 7
6 - 0
7 - 0
8 - 0
9 - 0

where the second number is the number of occurrences of the first number.

Code:

public static void main (String args[])
{
    Scanner chopper = new Scanner(System.in);
    System.out.println("Enter a list of number: ");

    int[] numCount = new int[10];
    int number;

    while (chopper.hasNextInt()) {
        number = chopper.nextInt();
        numCount[number]++;
    }

    for (int i = 0; i < 10; i++) {
        System.out.println(i + " - " + numCount[i]);
    }
}

但是在输入序列之后,我们必须输入一个非整数字符并按下“Enter”来终止Scanner并执行“for”循环。有什么方法可以让我们不必输入非整数字符来终止扫描程序?

最佳答案

您可以通过按 Enter 然后按 Control-D 退出。

如果您不想这样做,那么就没有其他方法可以使用 Scanner

您必须通过其他方式读取输入,例如使用 BufferedReader:

String line = new BufferedReader(new InputStreamReader(System.in)).readLine();
Scanner chopper = new Scanner(line);

更好(受 @user3512478 的方法启发),有两个扫描仪,没有 BufferedReader:

Scanner chopper = new Scanner(new Scanner(System.in).nextLine());

关于java - 将扫描仪与整数序列一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25701521/

相关文章:

java - 扫描仪未读取最后一个数字

java - 扫描 jTextArea 中的单词

java - 重定向的 input.txt 文件的内容未显示在命令提示符中

java - ScrollView Android 与图像

java - Completable Future什么时候将线程释放回线程池?

java - 使用扫描仪获取用户输入

用于 ArrayList 数据的 Java 扫描器

java - 使用 Stax 在 XML 文件中搜索特定字符串

java - 在android中更新firebase数据库

java - 如何使用 java.util.Scanner 正确扫描用户输入?