0

我需要创建一个采用整数命令行参数的程序。第一个参数将是 1 到 100(包括 1 到 100)之间的剩余参数的计数。然后它从剩余的参数中打印出输入的小于或等于 50 的数字计数和大于 50 的数字计数。

该代码仅在我在命令提示符中键入 0 或 1 时才有效。任何其他值都会返回 ArrayIndexOutOfBoundsException。我想如果我将数组设置为“count”,无论我在打印代码时输入多少数字,它都会返回,但它仍然无法正常工作。

任何人都可以对我现有的代码块提出建议吗?我是一个新手程序员,所以我不知道从哪里开始。我已经尝试更改数组值,但不断收到相同的错误。

public class Distribution100 {
  public static void main(String[] args) {

    int count = Integer.parseInt(args[0]);

    int[] array = new int[count];

    int low = 0;
    int high = 0;
    for (int i = 0; i < count; i++) {

      array[i] = Integer.parseInt(args[i]);

      if (array[i] >= 1 && array[i] <= 50) {
        low++;
      } else if (array[i] > 50 && array[i] <= 100) {
        high++;
      }
    }

    System.out.println(low + " numbers are less than or equal to 50.");

    System.out.println(high + " numbers are higher than 50.");

  }

}
4

1 回答 1

0

这段代码对我有用。请注意,我已经从您的代码中更改了一行 - 您有array[i] = Integer.parseInt(args[i]);,我将其更改为array[i] Integer.parseInt(args[i + 1]);,因为 i 从 0 开始并且args[0]是您的计数,而不是要检查的数字之一。

public static void main(String[] args) {

        int count = Integer.parseInt(args[0]);

        int[] array = new int[count];

        int low = 0;
        int high = 0;
        for (int i = 0; i < count; i++) {

            array[i] = Integer.parseInt(args[i + 1]);

            if (array[i] >= 1 && array[i] <= 50) {
                low++;
            } else if (array[i] > 50 && array[i] <= 100) {
                high++;
            }
        }

        System.out.println(low + " numbers are less than or equal to 50.");

        System.out.println(high + " numbers are higher than 50.");

    }
于 2021-09-21T19:37:52.797 回答