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

时间:2015-03-29 10:57:46

标签: java variables calculator

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

我正在创建一个简单的计算器并尝试将答案输出到 " Number" "操作" " 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);

输入这些数字和操作员返回时的输出" 5 + 5 = 5 + 5"而且我想回来" 5 + 5 = 10"。

2 个答案:

答案 0 :(得分:0)

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的读数,则可以将两者结合起来。

答案 1 :(得分:0)

计算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);