3 回答

TA貢獻(xiàn)1841條經(jīng)驗(yàn) 獲得超3個(gè)贊
您需要在 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貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超6個(gè)贊
在外部聲明參數(shù)并在 switch case 中設(shè)置。所以這段代碼會(huì)是這樣的;
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貢獻(xiàn)1859條經(jīng)驗(yàn) 獲得超6個(gè)贊
問題是您沒有遵循變量可見性范圍。您需要計(jì)算括號(hào) {} 這是一個(gè)通用示例。
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;
}
}
添加回答
舉報(bào)