-2
public static void main(String[] args) {

    int n;
    n = Integer.parseInt(args[0]);
    if(n>100)
    {
        System.out.println("The number is greater than 100.");
    }
}
Biffen
  • 6,249
  • 6
  • 28
  • 36
shanti
  • 3
  • 1

2 Answers2

1

The args array contains the arguments given to the program (command line parameters). You can give these either via:

  1. the project run settings in an IDE
  2. the command line

If you run your program without any arguments, the array will however be empty. Therefore, no item will be on index 0 and the ArrayIndexOutOfBoundsException is thrown.

If you want to fix this, you will either have to:

  1. pass at least one argument via one of the mentioned methods aboven.
  2. change your code so it does not depend on command line parameters.
PimJ
  • 38
  • 7
0

change your code this way:

public static void main(String[] args) {
    if(args != null && args.length > 0) {
    int n;
    n = Integer.parseInt(args[0]);
    if(n>100) {
        System.out.println("The number is greater than 100.");
    }
    }
}

If you want also to handle the fact that args[0] could not be an integer, you can change it this way:

public static void main(String[] args) {
        if(args != null && args.length > 0) {
        int n;
try {
        n = Integer.parseInt(args[0]);
        if(n>100) {
            System.out.println("The number is greater than 100.");
        }
catch(NumberFormatException e) {
System.err.println("Not a number");
}
        }
    }
ChaSIem
  • 493
  • 1
  • 6
  • 18