我正在尝试使用if语句构建一个基本计算器

时间:2016-09-28 19:08:53

标签: java if-statement calculator

我正在尝试为课堂制作一个基本的计算器。

我想出了下面的代码,但它只是添加了它。

即使我使用-*/

任何提示?

Scanner input = new Scanner(System.in);
    String num1, num2, operation, function;

    System.out.println("Enter a simple equation: ");
    function = input.nextLine();
    int firstspace = function.indexOf(" ");
    num1 = (function.substring(0,firstspace));
    int lastspace = function.lastIndexOf(" ");
    operation = (function.substring(firstspace,lastspace));
    num2= (function.substring(lastspace+1,function.length()));
    double n1 = Double.parseDouble(num1);
    double n2 = Double.parseDouble(num2);



    if (operation.equals(" + "));
    {
        System.out.println("your answer is " + (n1 + n2));
    }
    if  (operation.equals(" - "))
    {
        System.out.println("your answer is " + (n1 - n2));
    }

    if (operation.equals(" / "))
    {
        System.out.println("your answer is " + (n1 / n2));
    }
    if (operation.equals(" * "))
    {
        System.out.println("your answer is " + ( n1*n2));
    }

}

}

1 个答案:

答案 0 :(得分:1)

从我看到你的代码有这个问题

if (operation.equals(" + "));
{
    System.out.println("your answer is " + (n1 + n2));
}

这里放置一个半冒号,这意味着当你运行代码时,默认情况下会执行这个条件,这意味着无论你喜不喜欢,总会执行添加。

所以基本上你的代码应该是这样的

if (operation.equals("+" ))
            {
                System.out.println("your answer is " + (n1 + n2));
            }
            if  (operation.equals("-"))
            {
                System.out.println("your answer is " + (n1 - n2));
            }

            if (operation.equals("/"))
            {
                System.out.println("your answer is " + (n1 / n2));
            }
            if (operation.equals("*"))
            {
                System.out.println("your answer is " + ( n1*n2));
            }

希望这有帮助