简体   繁体   中英

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.

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 ie 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM