charliecane
charliecane

Reputation: 13

Java ArrayIndexOutOfBounds

Currently working on a student project. I want to figure out the highest number and sort it by bubble sort, the number is parsed from a JLabel, but I get this error everytime. Here is a code snippet:

    JLabel[] wuerfelsummen = new JLabel[7];
    wuerfelsummen[0] = player1_wuerfelsumme;
    wuerfelsummen[1] = player2_wuerfelsumme;
    wuerfelsummen[2] = player3_wuerfelsumme;
    wuerfelsummen[3] = player4_wuerfelsumme;
    wuerfelsummen[4] = player5_wuerfelsumme;
    wuerfelsummen[5] = player6_wuerfelsumme;

public int ermittleGewinner(JLabel[] w)
{
    int temp;
    int[] zahlen = new int[w.length];
    for(int i=0; i<=zahlen.length; i++)
    {
        if(w[i].getText() == null)
        {
            zahlen[i] = 99999999;
        }
        else
        {
            zahlen[i] = Integer.parseInt(w[i].getText());
        }
    }

    for(int i=1; i<zahlen.length; i++) 
    {
        for(int j=0; j<zahlen.length-i; j++) 
        {
            if(zahlen[j]>zahlen[j+1]) 
            {
                temp=zahlen[j];
                zahlen[j]=zahlen[j+1];
                zahlen[j+1]=temp;
            }

        }
    }

Upvotes: 0

Views: 85

Answers (3)

Dragondraikk
Dragondraikk

Reputation: 1679

for(int i=0; i<=zahlen.length; i++)

This is incorrect, as arrays are 0-indexed, meaning they reach from 0 to length-1.

Change it to

for(int i=0; i<zahlen.length; i++)

Interestingly enough, your other loops avoid this pitfall, although you will still have to be careful about the j+1 later on. Make sure that this can never be >= zahlen.length.

You could simply initialize j with 1 instead of 0 and then replace all occurences of j with j-1 and j+1 with j

Upvotes: 3

hagrawal7777
hagrawal7777

Reputation: 14658

ArrayIndexOutOfBounds expcetion comes when code tried to access an element of an array which is not present. In your code, since you are FOR looping one extra time for(int i=0; i<=zahlen.length; i++), you are getting this exception. Keep FOR loop as for(int i=0; i<zahlen.length; i++)

You have not to just check for zahlen[i] but also for w[i] because you are looping on length of zahlen and it may so happen that w is of lesser length then zahlen.

Upvotes: 0

GregH
GregH

Reputation: 5457

change "i<=zahlen.length" in your for loop to "i < zahlen.length".

remember arrays are 0 indexed so you are trying to access an element one index outside of how large your array is with the "<=" method you are currently using

The second loop should start at i=0 instead of i=1. By using i=1, you are again going to try to access one element past the size of your array

Upvotes: 0

Related Questions