intboolstring
intboolstring

Reputation: 7100

Swapping Value Program throws error

Just to be clear, I have done my research on the error that I'm getting, Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10. I have been looking on SO for a while and none of the solutions provided work. What is partially confusing me is the line where the error is being thrown. **This is not a duplicate thread from the threads with the **

I am writing a program that swaps the value of two indexes of an array (part of a greater sort program). I am getting the error Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10. There error is pointing to the line in my code if(data[i] > data[i+1]){. I can't figure out what is causing the error, but I know it is probably something very simple that I am missing.

public static int length = 10;
public static int[] data = new int[length];
data[0] = 1;
data[1] = 10;
data[2] = 5;
data[3] = 11;
data[4] = 9;
data[5] = 2;
data[6] = 7;
data[7] = 9;
data[8] = 8;
data[9] = 10;
public static void exchange(){
    int temp = 0;
    for(int i=0;i<length;i++){
        if(data[i] > data[i+1]){
            temp = data[i+1];
            data[i+1] = data[i];
            data[i] = temp;
        }
    }
}

Any help is appreciated:) Thanks in advanced

Upvotes: 1

Views: 45

Answers (3)

alphanumeric character
alphanumeric character

Reputation: 141

By doing i+1, you are trying to access an index of the array that does not exist when i equals length - 1 (9). You can't access the variable you are trying to the way you are doing it.

Upvotes: 3

Bethany Louise
Bethany Louise

Reputation: 646

On the final iteration of the for loop, i equals 9. Your if statement then tries to compare data[9] to data[10], which results in an exception because the highest index in data is 9.

Upvotes: 2

Elliott Frisch
Elliott Frisch

Reputation: 201439

Since you say i+1 on the next line, use something like

for(int i=0;i<length - 1;i++){
    if(data[i] > data[i+1]){

Alternatively, you could use something like

for(int i=1;i<length;i++){
    if(data[i-1] > data[i]){
        temp = data[i];
        data[i] = data[i-1];
        data[i-1] = temp;
    }

Upvotes: 3

Related Questions