简体   繁体   中英

Why am I getting java.lang.ArrayIndexOutOfBoundsException exception ?

Why does my code not work? I wanted the following: One enters a number and the program prints out all numbers until the entered number. It is part of a problem of a bigger code of mine. Thats why its important for me to do it with a while(true)-loop with a break and with an array that would later be printed out.

Letting it run, after entering a number it only says:

"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at yt_brotcr_15ff.yt_brotcr_19_Schmierzettel5.main(yt_brotcr_19_Schmierzettel5.java:14)"

What is the problem?

Here is the code:

package yt_brotcr_15ff;

import java.util.Scanner;

public class yt_brotcr_19_Schmierzettel5 {
    public static void main (String[] args) {
        int i = 0;
        int hochzähl = 1;
        int eingabeB;
        Scanner s = new Scanner(System.in);
        eingabeB = s.nextInt();
        int[] zahlArray = new int[eingabeB];
        while (true) {
            zahlArray[i] = hochzähl;
            if (i > eingabeB) {
                break;
            }
            i++;
            hochzähl++;
        }
        for (int j = 0; j > eingabeB; j++) {
            System.out.println(zahlArray[j]);
    }
    }
}   

Here's your problem....

        zahlArray[i] = hochzähl;

This line will error if i is greater or equal to eingabeB .

Your check must happen first:

        if (i >= eingabeB) {
            break;
       }
        zahlArray[i] = hochzähl

Notice the >= not >

The error:

java.lang.ArrayIndexOutOfBoundsException

is being thrown by this:

int[] zahlArray = new int[eingabeB];
    while (true) {
        zahlArray[i] = hochzähl;
        if (i > eingabeB) {
            break;
        }
        i++;
        hochzähl++;
    }

The first line creates an array with eingabeB entries, starting with 0. Therefore the last entry has index eingabeB-1 , and not eingabeB as your code expects.

There are several ways around this, you could try:

if (hochzähl > eingabeB) { // code

for example.

Because, you are trying to access array index beyond its size. Please note, array index start from 0 and goes till length -1 . So, if zahlArray size is 4, so maximum array index can be 3 .

Now, imagine i=3 , which is greater than 4. So, (i > eingabeB) would false . So, loop continues and increment i value to 4. Now, as you know, you can't access index 4 of array size 4 , accessing this index will give you mentioned exception.

zahlArray[i] = hochzähl;
if (i > eingabeB) 
{
   break;
}
i++;
hochzähl++;

To correct this, you should move (i > eingabeB) after incrementing i value. It should be like

zahlArray[i] = hochzähl;
i++;
if (i > eingabeB) 
{
   break;
}
hochzähl++;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM