【问题标题】:I am trying to build a basic calculator using if statements我正在尝试使用 if 语句构建一个基本计算器
【发布时间】:2016-09-28 19:08:53
【问题描述】:

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

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

即使我使用-*/

有什么建议吗?

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));
    }

}

}

【问题讨论】:

  • 欢迎来到 SO :-) 你试过调试你的代码吗?

标签: java if-statement calculator


【解决方案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));
            }

希望对你有帮助

【讨论】:

    猜你喜欢
    • 2022-12-17
    • 1970-01-01
    • 2021-05-27
    • 2020-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-04
    • 2014-05-23
    相关资源
    最近更新 更多