我正在制作一个简单的程序,该程序使用 1和10 之间的随机数生成随机数学问题。运算符在 +,-和* 之间也将是随机的。当我尝试使用case语句并返回操作值并打印问题(最后)时,它说没有 operation 变量。
int number1 = (int)(Math.random()* 10) + 1;
int number2 = (int)(Math.random()* 10) + 1;
int operator = (int)(Math.random()* 3) + 1;
switch (operator){
case 1: {
String operation = "+";
int correctResult = number1 + number2;
break;
}
case 2: {
String operation = "-";
int correctResult = number1 - number2;
break;
}
case 3: {
String operation = "*";
int correctResult = number1 * number2;
break;
}
}
System.out.print(number1+operation+number2+": ");
String studentAnswer = scanner.next();
答案 0 :(得分:3)
您需要在od开关块外部声明操作:
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();
答案 1 :(得分:1)
在外部声明参数并将其设置在开关盒中。所以这段代码就是这样;
IEnumerable<Expense>
答案 2 :(得分:1)
问题在于您未遵循变量可见性范围。您需要计算括号{}这是一个通用示例。
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;
}
}
答案 3 :(得分:-2)
因为操作变量在每个case块内定义,因此在这些块外不可见。在切换之前声明一个变量,并在case块内修改其值。
operation
变量仅在每种情况下定义。