Java新手试图编写计算器

Java新手试图编写计算器,java,math,calculator,Java,Math,Calculator,我是Java新手,我正在尝试编写一个计算器。这些数字没有计算出来,我也不知道为什么会发生这种情况 这是我的密码: import java.util.Scanner; public class Calculator { public static void main(String[] args){ System.out.println("Type in any 2 numbers: "); Scanner math = new Scanner(Syste

我是Java新手,我正在尝试编写一个计算器。这些数字没有计算出来,我也不知道为什么会发生这种情况

这是我的密码:

import java.util.Scanner;

public class Calculator {
    public static void main(String[] args){

        System.out.println("Type in any 2 numbers: ");
        Scanner math = new Scanner(System.in);
        int number = math.nextInt();
        int num2 = math.nextInt();

        System.out.println("Which operation would you like to use? (+,-,*,/)");
        String oper = math.next();

        if (oper == "+"){
            int total = number + num2;
            System.out.println(total);
        }
        else if (oper == "-"){
            int total = number - num2;
            System.out.println(total);
        }
        else if (oper == "*"){
            int total = number * num2;
            System.out.println(total);
        }
        else if (oper == "/"){
            int total = number / num2;
            System.out.println(total);
        }
    }

}

您应该使用Java中的equals方法来比较字符串。 在类中使用“==”时,它只比较引用,不比较值。 这应该适用于此修复

public class Calculator {
    public static void main(String[] args){

        System.out.println("Type in any 2 numbers: ");
        Scanner math = new Scanner(System.in);
        int number = math.nextInt();
        int num2 = math.nextInt();

        System.out.println("Which operation would you like to use? (+,-,*,/)");
        String oper = math.next();

        if (oper.equals("+")){
            int total = number + num2;
            System.out.println(total);
        }
        else if (oper.equals("-")){
            int total = number - num2;
            System.out.println(total);
        }
        else if (oper.equals("*")){
            int total = number * num2;
            System.out.println(total);
        }
        else if (oper.equals("/")){
            int total = number / num2;
            System.out.println(total);
        }
    }

@Ran Koretzki是对的,我对您的代码有一个可能的改进。您正在读取来自用户的输入并将其分配给“整数值”。即使此代码没有提示任何编译时或运行时错误,代码中也存在逻辑问题

将两个整数相除,并将结果赋给一个整数。当您尝试将两个整数除并且没有余数时,这种方法非常有效。但若除法过程中有余数,你们将失去这个余数或分数。为了解决这个问题,您应该将输入读入双值,并将操作结果分配到双变量中