I wanted to try to set one argument args[0] , depending on which array will be displayed in direct or reverse order.
On the line, if(args[0].compareTo("First") == 0) throws ArrayIndexOutOfBoundsException: 0 .

What is the problem?

 public class Main { public static void main(String[] args) { int[] massive = { 1, 2, 3, 4, 5 }; if (args[0].compareTo("First") == 0) { for (int i = 0; i < massive.length; i++) { System.out.println(massive[i]); } } else if (args[0].compareTo("Second") == 0) { for (int i = massive.length; i > 0; i--) { System.out.println(massive[i]); } } else if (args[0] == null || args.length == 0) { System.out.println("Third"); } } } 
  • By code, it says that in the args [] array there is no element 0, by code I do not see the args myself. - Denis Kotlyarov
  • In theory, args [0] will be given on the command line. - Ibuprofenn
  • one
    @Ibuprofenn show how you run from the command line - Yuriy SPb
  • one
    int i = massive.length; - array indices from 0 to length - 1 - zRrr
  • 2
    And a couple of moments not on the question itself: 1. From the English "massive" - ​​translated as "massive." To refer to an array, use the word "array". 2. Must be args.length == 0 || args[0] == null args.length == 0 || args[0] == null , and not vice versa, because in your version the second condition is meaningless. - Regent

2 answers 2

So, protection against ArrayIndexOutOfBoundsException added, checks are modified (no dependencies on the argument register), the first cycle is replaced with for-each , the second is changed so that all elements of the array are output and the error does not crash.

  public static void main(String[] args) { int[] array = {1, 2, 3, 4, 5}; if (args.length == 1 && args[0].equalsIgnoreCase("First")) { for (int anArray : array) System.out.println(anArray); } else if (args.length == 1 && args[0].equalsIgnoreCase("Second")) { for (int i = array.length-1; i >= 0; i--) System.out.println(array[i]); } else if (args.length == 0) System.out.println("Third"); } 

It is necessary to run through the console, using the java Main First / Second command. If there is a possibility to set input parameters via IDE, such as in Intellij IDEA, then you can set them like this: Run -> Edit Configuration -> Application in the Program Arguments field you specify the argument (if There are several arguments, it is necessary to specify separated by spaces)

  • What about this comment , it is correct, and your code will drop out of range - pavlofff

Most likely you do not correctly pass the parameters when starting the program. This needs to be done like this.

 java <Название класса с методом main> <первый параметр> <второй параметр> 

Read more about it here.