The Count of Remaining Arguments

186 Views Asked by At

I need to create a program that takes integer command-line arguments. The first argument would be the count of the remaining arguments that are between 1 and 100 (inclusive of 1 and 100). It then prints out the count of numbers entered that are less than or equal to 50 and the count of numbers that are greater than 50 from those remaining arguments.

The code only works if I type 0 or 1 into the command prompt. Any other value returns an ArrayIndexOutOfBoundsException. I thought if I set my array equal to "count", it would return however many numbers I typed out when printing my code, but it's still not working.

Can anyone make suggestions to my existing code block? I'm a novice programmer, so I'm at a loss at where to start. I've tried changing the array value around but keep getting the same error.

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.");

  }

}
1

There are 1 best solutions below

9
On

This code worked for me. Notice that I've changed one line from your code - you had array[i] = Integer.parseInt(args[i]);, and I changed it to array[i] Integer.parseInt(args[i + 1]);, as i starts at 0 and args[0] is your count, not one of the numbers to check.

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.");

    }