首页 > 解决方案 > 分配给 y 的值 x 从未在 switch 语句中使用?

问题描述

public void operationOnClick(View view){
        int operandOneValue = Integer.valueOf(operandOne.getText().toString());
        int operandTwoValue = Integer.valueOf(operandTwo.getText().toString());
        int resultValue = 0;
        Button op = (Button)view;
        String operation = op.getText().toString();

        switch(operation){
            // now i change the keyword 'return' with 'break'
            // i got the problem.
            case "+" : resultValue = operandOneValue+operandTwoValue;return;
            case "-" : resultValue = operandOneValue-operandTwoValue;return;
            case "*" : resultValue = operandOneValue*operandTwoValue;return;
            case "/" : resultValue = operandOneValue/operandTwoValue;return;
        }
        result.setText(String.valueOf(resultValue));
    }

从未使用分配给“resultValue”的值operandOneValue+opearndTwoValue?我无法弄清楚错误?

标签: javaandroid

解决方案


在您的 switch 语句中,将 every 替换return;break;退出 switch 的信号,但其余代码将运行。当您return在 void 方法中编写时,当它到达时,意味着您正在脱离方法本身,因此不会读取超过它的代码。在这种情况下,如果您的 switch case 匹配,您将永远无法使用该setText方法。


推荐阅读