-2

Hello i tried to compile my Code but this error Code appears: Bughunt04.Java:28: error: variable index might not have been initialized a[index] = index;

This is my Code

if (args.length != 2){
        System.out.println("ERROR");
        return;
    }

    System.out.println("Eindimensionaler Fall");
    int z = Integer.parseInt(args[0]);

    int a[] = new int[z];
    // Initialisieren des Arrays (die genauen Werte sind nicht wichtig)
    int index;
    for (z = 0; z < z; z++){
        a[index] = index;
    }

    index = 1;
    while (index < z/2){
        // swap tauscht in a die Elemente an den beiden uebergebenen Stellen
        a = swap(a, index, z-index);
        index++;
    } 

2 Answers2

2

You have to initialize your variable index before you use it the first time, basically that what the compilation error says.

int index = 0;
Glains
  • 2,773
  • 3
  • 16
  • 30
  • and what sense does the loop make after that statement? – luk2302 Nov 02 '18 at 12:09
  • @luk2302 I have made no assumption about the rest of the code since the OP did not provide further details. Of course, the loop is superflous. – Glains Nov 02 '18 at 12:12
  • after i edit that with your advice, the Compilation works. But, when i try to run it i get an error which says >Java.lang.ArrayIndexOutOfBoundException: -1 at Bughunt04.main(Bughunt04.java:42) – newcoder98 Nov 02 '18 at 12:16
0

Considering above two suggestions, I see you are trying to reverse an array. It can be done in the following way.

int index = 0;
for(int index=0;index<z;index++) {
    a[index] = index;
}
index = 0;
while (index < z/2){
    a = swap(a, index, z-index-1);
    index++;
} 
Hrudayanath
  • 474
  • 4
  • 18
  • @newcoder98 , if you get Java.lang.ArrayOutOfBoundException it means you are accessing array with illegal index. Ex- int[] a = new int[2]; valid memory accesses are a[0], a[1], if we try to access a[-1] or a[2] etc,. (other than a[0],a[1]) compiler will throw above mentioned error. – Hrudayanath Nov 02 '18 at 13:29