为什么变量eachLetter
在我在第二个循环中引用时是未知的?
import java.util.*;
public class Main {
public static void main(String [] args) {
String myName = ("Yourname");
int maxLength = myName.length() - 1;
for (int loops = 0; loops <= maxLength; loops++) {
char[] eachLetter = myName.toCharArray();
System.out.print(loops);
System.out.print(eachLetter[loops]);
}
System.out.println("");
System.out.println("next loop");
for (int loops = maxLength; loops <= 0; loops--) {
System.out.print(loops);
System.out.print(eachLetter[loops]);
}
}
}
答案 0 :(得分:2)
因为它只存在于第一个循环范围内。你必须在进入第一个循环之前声明它。
char[] eachLetter = new char[maxLength];
for (int loops=0; loops <= maxLength; loops++) {
eachLetter = myName.toCharArray();
}
for (int loops= maxLength; loops<=0; loops--) {
(..)
}
答案 1 :(得分:1)
首先,让我们为您的代码设置格式,使其清晰易读:
public static void main(String[] args) {
String myName = ("Yourname");
int maxLength = myName.length() - 1;
for (int loops = 0; loops <= maxLength; loops++) {
char[] eachLetter = myName.toCharArray();
System.out.print(loops);
System.out.print(eachLetter[loops]);
}
System.out.println("");
System.out.println("next loop");
for (int loops = maxLength; loops <= 0; loops--) {
System.out.print(loops);
System.out.print(eachLetter[loops]);
}
}
现在,在Java中 - 就像在Option Explicit
的VBA中一样 - 每个变量必须在范围中声明可见。
在Java范围内,大致如下:
{
char[] thing = ...
thing[i]...
}
//error
thing[i]
这是因为大括号中的第二个thing[i]
在您的示例中,您在 eachLetter
循环中声明for
- 每次迭代都有自己的实例。您正尝试在循环外部访问它。唯一的方法是在更宽的范围中声明它 - 即在下一组花括号中,方法:
public static void main(String[] args) {
String myName = ("Yourname");
int maxLength = myName.length() - 1;
char[] eachLetter = ...
for (int loops = 0; loops <= maxLength; loops++) {
eachLetter = myName.toCharArray();
但真正的问题是为什么你这样做。每次for
循环迭代时,您都会获得不同 char[]
。您只能从循环外部访问最后一个。