Happy Dog
Happy Dog

Reputation: 87

Error when using for-loop and String array

It has error on the second for in the array Alltext - in the error it says that it can't find the symbol of Alltext and my code can't seem to initialize because of that.

I have tried placing the second for inside the first for it didn't work. I even tried to change some way like making key code for the String array.

    for (int i = 1; i <= n; i++) {

        System.out.print("Input number : ");
        a = Masuk.readLine();
        n = Integer.parseInt(a);

        System.out.print("Input Text : ");
        a = Masuk.readLine();

        String[] Alltext = {a+" "+n};
    }

    for (String i : Alltext) {

        System.out.println(i);
    }

I'm expecting the output is when i'm inputting the number and text it will show all of it in the Alltext array.

Upvotes: 1

Views: 215

Answers (1)

uneq95
uneq95

Reputation: 2228

Because the scope of Alltext is only inside the first for loop as you have declared it inside the first loop. Hence your code doesn't know that any variable of the name Alltext exists outside that loop.

But if you declare it outside, you wont be able to initialise the array in the loop i.e. you can not do this Alltext = {a+" "+n};. Arrays can only be initialised once while declaring. Use an ArrayList instead, if it serves your use case.

You could do something like below:

System.out.print("Total Line : ");
a = Masuk.readLine();
n = Integer.parseInt(a);

String[] Alltext = new String[n];
for(int i = 1;i<=n;i++) {

System.out.print("Input number : ");
a = Masuk.readLine();
n = Integer.parseInt(a);

System.out.print("Input Text : ");
a = Masuk.readLine();

 Alltext[i-1]= a+" "+n;//i-1 because loop starts from 1

}
for(String i : Alltext){
 System.out.println(i);
}

Upvotes: 2

Related Questions