我正在编写一个程序来从控制台获取一系列整数,例如
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/