[英]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. 它的第二个错误
for
在阵列Alltext
-错误它说,它无法找到的符号Alltext
,似乎我的代码不能因为这个初始化。
I have tried placing the second for
inside the first for
it didn't work. 我试图把第二个
for
第一内侧for
没有奏效。 I even tried to change some way like making key code for the String array. 我什至尝试更改某种方法,例如为String数组编写键代码。
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. 我期望输出是当我输入数字和文本时,它将在
Alltext
数组中显示所有内容。
Because the scope of Alltext
is only inside the first for
loop as you have declared it inside the first loop. 因为
Alltext
的作用域仅在第一个for
循环内,所以您已在第一个循环内声明了它。 Hence your code doesn't know that any variable of the name Alltext
exists outside that loop. 因此,您的代码不知道名称
Alltext
任何变量Alltext
存在于该循环之外。
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};
但是,如果在外部声明它,则将无法在循环中初始化该数组,即,您将无法执行此操作
Alltext = {a+" "+n};
. 。 Arrays can only be initialised once while declaring.
数组只能在声明时初始化一次。 Use an ArrayList instead, if it serves your use case.
如果适合您的用例,请改用ArrayList。
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.