Java 尝试编写计算器代码的菜鸟

Java Rookie Attempting to code a 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(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);
        }
    }

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

您将两个整数相除并将结果赋给一个整数。当您尝试除以两个整数并且没有余数时,这种方法很有效。但是如果在除法过程中有余数,你就会失去这个余数或分数。为了解决这个问题,您应该将输入读入双精度值并将运算结果分配给双精度变量。