我的任务是获取数字并打印它们的出现次数。
我必须使用整数0
来终止进程,但我使用字符串x
进行处理。
这是我的代码:
import java.util.Scanner;
public class yasf{
public static void main(String[] args) {
int[] numbers = new int[101];
int num;
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number between 0-100 inclusive. x terminates:");
String numString = scan.nextLine();
// The input treminated with x;
while (!numString.equalsIgnoreCase("x")) {
num = Integer.parseInt(numString);
numbers[num] = numbers[num] + 1;
System.out.println("Enter a number between 0-100 inclusive. x terminates:");
numString = scan.nextLine();
}
for (int i = 0; i <= 100; i++) {
if (numbers[i] != 0 && numbers[i] == 1)
System.out.println(i + ": " + numbers[i] + " time");
else if (numbers[i] > 1 && numbers[i] != 0)
System.out.println(i + ": " + numbers[i] + " times");
else
System.out.print("");
}
}
}
我该怎么做?
答案 0 :(得分:1)
如果您仍想接受“0”作为有效输入,请删除
的第一个实例System.out.println("Enter a number between 0-100 inclusive. x terminates:");
String numString = scan.nextLine();
并使你的主要while循环看起来像这样
do{
System.out.println("Enter a number between 0-100 inclusive. x terminates:");
numString = scan.nextLine();
num = Integer.parseInt(numString);
numbers[num] = numbers[num]+1;
}while (!numString.equalsIgnoreCase("0"));