简单计算器:加法输出错误

时间:2018-12-29 07:36:11

标签: java

我是一个初学者,我正在尝试用java做一个简单的计算器。一切正常,除了Addition输出错误(例如1 + 1 = 1.01.0)。这是我的代码示例

package Package;
import java.util.Scanner;
public class SimpleCalculator {

    public static void main(String[] args) {
    Scanner input = new Scanner(System.in);


    System.out.println("Enter Equation:");
    double num1 = input.nextDouble();


    String oper = input.next();
    String plus, minus, divide, modulus, multiply;
    plus = "+";
    minus = "-";
    divide = "/";
    multiply = "*";
    modulus = "%";

        //Everything is the same but addition seems to have wrong output
        if (oper.equals(plus))
        {
            double num2 = input.nextDouble();
            System.out.println("= " + num1 + num2); 
        }
        else if (oper.equals(minus))
        {
            double num2 = input.nextDouble();
            System.out.println(num1 - num2);

1 个答案:

答案 0 :(得分:1)

您正在打印字符串num1num2,而不是计算结果。

当您打印出一个字符串(在您的情况下为"="时,Java会将添加到它的任何数字也视为字符串)。

要解决此问题,只需将您的计算添加到括号中,以使Java可以分别计算它们:

System.out.println("=" + (num1 + num2));