3 回答
TA贡献1841条经验 获得超3个赞
您需要在 od switch 块之外声明操作:
int number1 = (int)(Math.random()* 10) + 1;
int number2 = (int)(Math.random()* 10) + 1;
int operator = (int)(Math.random()* 3) + 1;
String operation = null; // move outside of switch block
int correctResult; // move outside of switch block
switch (operator){
case 1: {
operation = "+";
correctResult = number1 + number2;
break;
}
case 2: {
operation = "-";
correctResult = number1 - number2;
break;
}
case 3: {
operation = "*";
correctResult = number1 * number2;
break;
}
}
System.out.print(number1+operation+number2+": ");
String studentAnswer = scanner.next();
TA贡献1848条经验 获得超6个赞
在外部声明参数并在 switch case 中设置。所以这段代码会是这样的;
int number1 = (int) (Math.random() * 10) + 1;
int number2 = (int) (Math.random() * 10) + 1;
int operator = (int) (Math.random() * 3) + 1;
//initalize value which is changing in swich case statement and set initializing value
String operation = "";
int correctResult = 0;
switch (operator) {
case 1: {
operation = "+";
correctResult = number1 + number2;
break;
}
case 2: {
operation = "-";
correctResult = number1 - number2;
break;
}
case 3: {
operation = "*";
correctResult = number1 * number2;
break;
}
}
System.out.print(number1 + operation + number2 + ": ");
String studentAnswer = scanner.next();
TA贡献1859条经验 获得超6个赞
问题是您没有遵循变量可见性范围。您需要计算括号 {} 这是一个通用示例。
public void exampleScopeMethod {
String localVariable = "I am a local Variable";
{
String nextScope = " NextScope is One level deeper";
localVariable += nextScope
}
{
String anotherScope = "Is one level deeper than local variable, still different scope than nextScope";
//Ooops nextScope is no longer visible I can not do that!!!
anotherScope +=nextScope;
{ one more scope , useless but valid }
}
//Ooopppsss... this is again not valid
return nextScope;
// now it is valid
return localVariable;
}
}
添加回答
举报