对扫描仪中的项目进行计数

  • 本文关键字:项目 扫描仪 java
  • 更新时间 :
  • 英文 :


我已经声明了一个名为 Scan 的Scanner对象

我想提示用户输入他们喜欢的任意数量的项目:

ie: Enter items: 1 2 6 4 3 12

如何计算输入了多少个数字?例如,上面的输出应该是 6,因为有 6 个数字

我试过了

int count = 0;
while(Scan.hasNextInt()){
count++ };

您可以在空格上拆分行并获取零件数。

final String line = Scan.nextLine();
if(line.trim().isEmpty()){
System.out.println("Nothing entered");
} else {
final String[] parts = line.split("\s+");
System.out.println(parts.length);
}

演示:https://ideone.com/zgr6zM

要将部件转换为 int 数组,可以使用Arrays.stream.mapToInt

final int[] nums = Arrays.stream(parts).mapToInt(Integer::parseInt).toArray();

演示:https://ideone.com/WevrTw

您需要实际调用scanner.nextInt()否则扫描仪的"指针"将永远不会超过第一个数字。

jshell> while(scanner.hasNextInt()) {
...> count++;
...> scanner.nextInt();
...> }
1 2 3 4 5 6

jshell> count
count ==> 6

您可以按如下方式阅读数字。

2 3 12 3 1 2
2 29 122 q

重点是hasNextInt将继续从控制台读取,直到输入非整数。

Scanner scan = new Scanner(System.in);
List<Integer> numbs = new ArrayList<>();
System.out.println("Enter ints followed by any letter to quit");
while (scan.hasNextInt()) {
numbs.add(scan.nextInt());
}
System.out.println("The following " + numbs.size() + " numbers were entered.");
System.out.println(numbs);

将打印上面的示例输入。

The following 9 numbers were entered.
[2, 3, 12, 3, 1, 2, 2, 29, 122]

最新更新