【问题标题】:calculator wont take user input计算器不会接受用户输入
【发布时间】:2016-03-17 18:52:03
【问题描述】:

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

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

}

【问题讨论】:

标签: java input calculator


【解决方案1】:

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

所以calcType.equals("*") 表示相等或!calcType.equals("*") 检查它们是否不相同。

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

【讨论】:

    【解决方案2】:

    一旦按照@redFIVE 的建议调整您的代码(将!= 替换为!myVar.equals(str)),请确保将您的OR(||)替换为AND(&&)。

    考虑以下几点:

    if (!calcType.equals("+") || !calcType.equals("*") || ...)

    如果输入为"+",则条件仍会通过,因为calcType 不等于"*",并且逻辑计算结果为TRUE。

    当您使用 AND:if (!calcType.equals("+") && !calcType.equals("*") && ...) 时,您应该会看到预期的结果。


    但是,您当前代码的主要问题是由于您滥用!= 来比较Strings。解决这个问题,您至少可以使用调试器查看为什么上述逻辑可能会失败或产生意外结果。

    【讨论】:

    • 很酷,所以我还需要以同样的方式制作“else if”语句。 calcType.equals("+")。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-05
    • 1970-01-01
    • 2018-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-18
    相关资源
    最近更新 更多