-2

I always get this Error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4

    Output in = new Output();
    int numbers[] = new int[4];
    numbers[0] = in.inInt("1. Zahl: ");
    numbers[1] = in.inInt("2. Zahl: ");
    numbers[2] = in.inInt("3. Zahl: ");
    numbers[3] = in.inInt("4. Zahl: ");     
    numbers[4] = in.inInt("5. Zahl: ");     
    int max = 0;

    for(int counter = 0; counter < numbers.length; counter++) {
        if (numbers[counter] > max) {
            max = numbers[counter]; 
        }   
    }

    System.out.println("Die größte eingegebene Zahl ist: " + max);
iTzMine
  • 1
  • 4

1 Answers1

0

Note that valid array indices go from 0 to array-length - 1 since arrays are 0-based. So in your for loop, change counter <= numbers.length to counter < numbers.length

Now problem

This question already has an answer here: What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? 7 answers I always get this Error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4

Output in = new Output();
int numbers[] = new int[4];
numbers[0] = in.inInt("1. Zahl: ");
numbers[1] = in.inInt("2. Zahl: ");
numbers[2] = in.inInt("3. Zahl: ");
numbers[3] = in.inInt("4. Zahl: ");     
numbers[4] = in.inInt("5. Zahl: ");   // ****** here****
int max = 0;

Again, arrays go from 0 to length - 1. You're trying to put something into index at the length position, and that should give you an AIOOB error.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • i still get the same error with this – iTzMine Jan 10 '16 at 22:56
  • 1
    @iTzMine: Please [edit your question](http://stackoverflow.com/posts/34711707/edit) (click on the link) and show us your latest code, the code that is still causing the error. – Hovercraft Full Of Eels Jan 10 '16 at 22:58
  • 1
    @iTzMine Then the error is elsewhere. Read carefully the linked question to see what causes this exception. – Tunaki Jan 10 '16 at 22:58
  • @iTzMine: new problem, and you need to re-read my answer, especially the part about arrays going from 0 to length - 1. Your array is size 4 and you're putting **five items into it**. Better still -- just use an ArrayList. – Hovercraft Full Of Eels Jan 10 '16 at 23:05
  • I deleted this line: numbers[4].... and now it works. Thank You! – iTzMine Jan 10 '16 at 23:07