java - 计算器不会接受用户输入

标签 java input calculator

一直在尝试制作一个简单的计算器加减乘除。但它不允许我进入计算部分。它总是说“计算类型不正确”,即使我键入 +、-、/或“” 我如何让扫描器理解 +、-、/、“”作为输入?谢谢

import java.util.Scanner;

public class Calculator {

    public void typeOfCalc(){
        Scanner user_input = new Scanner(System.in);
        System.out.print("What type of calculation do you want? \n Addition? type '+' \n Subtraction? type '-' \n Division? type '/' \n or Multiplication type '*' \n");
        String calcType = user_input.next().trim();
       if (calcType != "+" || calcType != "*" || calcType != "/" || calcType != "-"){
           System.out.println("Incorrect type of calculation, try again \n");
           typeOfCalc();
       }

        else if (calcType == "+"){

            System.out.print("Chose your first number \n");
            int num1 = user_input.nextInt();
            System.out.print("Chose your second number \n");
            int num2 = user_input.nextInt();
            System.out.print(num1 + " + " + num2 + " = \n" + (num1 + num2) + "\n");
        }
        else if (calcType == "-"){

            System.out.print("Chose your first number \n");
            int num1 = user_input.nextInt();
            System.out.print("Chose your second number \n");
            int num2 = user_input.nextInt();
            System.out.print(num1 + " - " + num2 + " = \n" + (num1 - num2) + "\n");
        }
        else if (calcType == "/"){

            System.out.print("Chose your first number \n");
            int num1 = user_input.nextInt();
            System.out.print("Chose your second number \n");
            int num2 = user_input.nextInt();
            System.out.print(num1 + " / " + num2 + " = \n" + (num1 / num2) + "\n");
        }
        else if (calcType == "*"){

            System.out.print("Chose your first number \n");
            int num1 = user_input.nextInt();
            System.out.print("Chose your second number \n");
            int num2 = user_input.nextInt();
            System.out.print(num1 + " * " + num2 + " = \n" + (num1 * num2) + "\n");
        }
    }

}

最佳答案

您需要使用 .equals() 来检查字符串是否相等。

因此 calcType.equals("*") 用于相等性或 !calcType.equals("*") 用于检查它们是否相同。

字符串是不可变的,所以当你使用==时,它是检查它是否是内存中的同一个字符串,而不是检查字符串的实际内容

关于java - 计算器不会接受用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34230650/

相关文章:

具有不固定延迟的Java计时器

html - `min-width` 不适用于表单 `input[type="button"]` 元素吗?

bison - 柔性/Bison : Why my rule is not regonized?

calculator - 如何在卡西欧 fx-991ES 计算器中计算 Mod b

java - else on if 语句没有通过

java - Java 中的 2D 平铺游戏优化

java - JTable onchange 事件

java - 用java将值输入到二维数组中

java - 在实现检测输入是否为整数的系统时遇到困难

c++ - 通过按空格键结束键盘输入数据,而不是输入键 c/c++