所以,我需要访问我在最后一个 if 语句中的 if 语句中分配的变量。我是 Java 初学者,感谢任何帮助:)
这是我的编译错误。
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The local variable a may not have been initialized
The local variable b may not have been initialized
The local variable c may not have been initialized
The local variable d may not have been initialized
The local variable e may not have been initialized
这是我的代码。我需要根据已经经过的迭代次数分配某个变量,并在最后一次迭代分配变量后访问这些变量。
public static void main(String[] args){
String a;
String b;
String c;
String d;
String e;
Scanner s = new Scanner(System.in);
for( int loop = 1; loop <= 6; loop++ ){
if(loop == 1){
System.out.println("Please input a grade.");
a = s.nextLine();
System.out.println("You said,"+a);
continue;
}
if(loop == 2){
System.out.println("Please input a grade.");;
b = s.nextLine();
System.out.println("You said,"+b);
continue;
}
if(loop == 3){
System.out.println("Please input a grade.");
c = s.nextLine();
System.out.println("You said," +c);
continue;
}
if(loop == 4){
System.out.println("Please input a grade.");
d = s.nextLine();
System.out.println("You said," +d);
continue;
}
if(loop == 5){
System.out.println("Please input a grade.");
e = s.nextLine();
System.out.println("You said," +e);
continue;
}
if(loop == 6){
System.out.println("Grade 1."+a);
System.out.println("Grade 1."+b);
System.out.println("Grade 1."+c);
System.out.println("Grade 1."+d);
System.out.println("Grade 1."+e);
}
}
}
最佳答案
您正在声明并尝试访问该字符串。如果要使用变量,则必须首先初始化它们。您可以通过这样做来声明它们:
String a;
您还需要像这样初始化它们:
String a = "";
在尝试访问它们之前先初始化它们,否则 Java 编译器会不高兴!
关于java - 如何在同一级别的 if 语句中分配/访问变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29636066/