Java - 使用变量获得计算的答案

Java - Getting the answer to a calculation using variables

如何return计算的答案,其中使用的两个数字和运算符存储在变量中(来自用户的输入)。

我正在创建一个简单的计算器并尝试将答案输出到 "Number" "Operator" "Number2" 可以是任何内容,具体取决于用户输入的内容。

int Number;
int Number2;
int Operator;
String OperatorString;

do 
{
    System.out.println("Enter a number");
    Number = UserInputScanner.nextInt();

    System.out.println("1. + \n");
    System.out.println("2. - \n");
    System.out.println("3. * \n");
    System.out.println("4. / \n");

    Operator = UserInputScanner.nextInt(); 

       switch (Operator) {
        case 1:  OperatorString = "+";          
                 break;
        case 2:  OperatorString = "-";
                 break;
        case 3:  OperatorString = "*";
                 break;
        case 4:  OperatorString = "/";
                 break;
        default: OperatorString = "Invalid Operator";
                 break;
    }
    System.out.println(OperatorString);

    System.out.println("Enter another number");
    Number2 = UserInputScanner.nextInt();       

    Answer = "Number" + "OperatorString" + "Number2";
    System.out.println(Number + OperatorString + Number2 + "=" + Answer);

输入这些数字和运算符时的输出 returns "5+5=5+5" 我正在尝试 return "5+5=10".

Java 没有提供使用运算符计算 String 表达式以生成结果值的内置方法,因此您需要另一个开关来计算 Answer:

switch (Operator) {
    case 1:  Answer = Number + Number2;
             break;
    case 2:  Answer = Number - Number2;
             break;
    case 3:  Answer = Number * Number2;
             break;
    case 4:  Answer = Number / Number2;
             break;
    default: Answer = 0;
             break;
}

开关的结构与读取第二个数字之前的结构相同,因此如果将 Number2 的读数移动到开关之前,则可以将两者结合起来。

在 Switch 块本身中计算答案

int Number;
int Number2;
int Operator;
String OperatorString;

do 
{
System.out.println("Enter a number");
Number = UserInputScanner.nextInt();

System.out.println("1. + \n");
System.out.println("2. - \n");
System.out.println("3. * \n");
System.out.println("4. / \n");

Operator = UserInputScanner.nextInt(); 
System.out.println("Enter another number");
Number2 = UserInputScanner.nextInt(); 
   switch (Operator) {
    case 1:  OperatorString = "+"; 
             Answer = Number + Number2;
             break;
    case 2:  OperatorString = "-";
             Answer = Number - Number2;
             break;
    case 3:  OperatorString = "*";
             Answer = Number * Number2;
             break;
    case 4:  OperatorString = "/";
             Answer = Number / Number2;
             break;
    default: OperatorString = "Invalid Operator";
             break;
}
System.out.println(OperatorString);




System.out.println(Number + OperatorString + Number2 + "=" + Answer);