0

So basically I want to make an algorithm to shuffle my array, all I have is this:

import java.util.*;

class MixUp{

    public static void main(String args[]){

        int temp, i=0;
        boolean flag=true;
        int Table[] = new int[5];
        Scanner input = new Scanner(System.in);

        for(i=0; i<5; i++){
            System.out.println("Number? : ");
            Table[i] = input.nextInt();
        }

        for(i=0; i<5; i++){
            System.out.printf(Table[i] + "\t");
        }

        for(i=0; i<5; i++){
            temp = Table[i+1];
            Table[i+1] = Table[Table.length-i];
            Table[Table.length-i] = temp;
            if(i+1 == Table.length-i) break;
        }

        for(i=0; i<5; i++){
            System.out.printf(Table[i] + "\t");
        }
     }
}

And it keeps popping up

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at MixUp.main(MixUp.java:17)

Michel
  • 26,600
  • 6
  • 64
  • 69
TheodJoan
  • 1
  • 1

3 Answers3

2

Your second last loop iterates while i<5, which is fine, but then attempts to access Table[i+1]. If i=4 this will result in an attempt to access Table[5], which, of course, is not a valid index.

One way to fixt that could be to change that loop's condition to i<4 instead of i<5.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
0
Table[Table.length-i];

This code will always crash when i=0

popiandro
  • 317
  • 1
  • 17
  • Shouldn't it take the price of the table's last slot, in this case Table[Table.length - i ] == Table[5]? – TheodJoan Oct 04 '15 at 00:09
  • An array of length=5 goes from 0 to 4. Table[5] is outside the array. You should write `Table[Table.length - i -1]` – popiandro Oct 04 '15 at 00:12
  • Changed it as below, still Exception in etc etc `for(i=0; i<5; i++){ temp = Table[i+1]; Table[i+1] = Table[Table.length-i-1]; Table[Table.length-i-1] = temp; if(i+1 == Table.length-i-1) break; }` – TheodJoan Oct 04 '15 at 00:16
0

Fixed It!

for(i=1; i<5; i++){
temp = Table[i];
Table[i] = Table[Table.length-i];
Table[Table.length-i] = temp;
if(i+1 == Table.length-i) break;
}

thanks for the help!

TheodJoan
  • 1
  • 1