为什么在case语句Java中不能返回值

时间:2018-09-09 20:06:52

标签: java

我正在制作一个简单的程序,该程序使用 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();    

4 个答案:

答案 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)

As JB Nizet said above

  

因为操作变量在每个case块内定义,因此在这些块外不可见。在切换之前声明一个变量,并在case块内修改其值。

operation变量仅在每种情况下定义。

相关问题