-2

The problem I'm running into is that my compiler states that 10 is out of bounds. But how can it be out of bounds if that is the array length i am setting it to?

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

  int arrayLength = Integer.parseInt(args[10]); //set array length
  int[] array = new int[arrayLength]; /make array
  int length = args.length; //the array length to be put in for loop
  System.out.printf("%s%8s\n", "Index", "Value");
  for( int counter = 0; counter < length; counter++){
  System.out.printf("%5d%8d\n", counter, array[counter]);

   }

}
}
Balwinder Singh
  • 2,272
  • 5
  • 23
  • 34
  • Are you sure the compiler is throwing the error or the JVM when you run the application? – Luiggi Mendoza Feb 28 '18 at 03:22
  • It's not your compiler, it's your running application. How many parameters are you passing to the running application? I'm sure it's less than 10, because you are looking for the 11-th parameter (index 10) and it's not there. – Sergey Kalinichenko Feb 28 '18 at 03:24
  • Oh hi, this is what returns after I run it : Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10 – Chanelle Feb 28 '18 at 03:28
  • I should also say that i'm not sure how command line works. I just want to set my array length to 10 – Chanelle Feb 28 '18 at 03:29

2 Answers2

2

You will ArrayIndexOutOfBoundsException if you don't pass 11 arguments to the program. You are trying to get the integer value of index 10 of args array.

javaxplain
  • 65
  • 6
0

At what line does it fail? on Integer.parseInt(args[10]) ?
Does args.length == 11?

In your code:
- "length" is the number of arguments passed to your program (at least 11 I guess...)
- "arraylength" is the value of the 11th arguments, what it's value?

It seems you exchanged lengthand arraylength in the forloop

titou10
  • 2,814
  • 1
  • 19
  • 42
  • Yes exactly that, Interger.parseInt(args[10]). What i thought was that it would go into arrayLength and set my array to 10 – Chanelle Feb 28 '18 at 03:31