0

我的任务是获取数字并将它们与它们的出现一起打印。我必须用整数终止进程,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("");
    }

}

}

我怎样才能做到这一点?

4

1 回答 1

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"));
于 2013-01-04T19:57:04.350 回答