简单的计算器不打印答案?

时间:2013-01-24 12:34:39

标签: java

我的程序无效。你觉得怎么回事?

Scanner in = new Scanner(System.in);
    System.out.print("Enter first number: ");
    double num1 = in.nextDouble();
    System.out.print("Enter second number: ");
    double num2 = in.nextDouble();
    System.out.println("Enter operation to perform: ");
    String oper = in.next();

    if(oper == "add" || oper == "addition" || oper == "+") {
        double sum = num1 + num2;
        System.out.printf("The sum of the two numbers is %d", sum);
    }

当我键入操作(String)时,程序终止。输出:

Enter first number: 12
Enter second number: 8
Enter operation to perform: 
"add"

Process completed.

我似乎无法找到错误,请帮忙?

9 个答案:

答案 0 :(得分:4)

永远不要将字符串与运算符==进行比较 - 这是错误的。请改用equals

if(oper.equals("add") || oper.equals("addition") || oper.equals("+")) {

答案 1 :(得分:2)

不要使用==使用equals方法:

if(oper.equals("add") || oper.equals("addition") || oper.equals("+")) 

==运算符用于比较内存空间中的地址而不是比较字符串的内容

答案 2 :(得分:2)

不要使用==比较字符串。始终使用equals()

if("add".equals( oper ) || "addition".equals( oper ) || "+".equals( oper ) ) {

// ...
}

使用==比较对象引用(或基本类型)。字符串是Java中的对象,因此当您比较operadd时,两者都指向不同的对象。因此,即使它们包含相同的值,与==的比较也会失败,因为它们仍然是不同的对象。

答案 3 :(得分:1)

if(oper == "add" || oper == "addition" || oper == "+") {

应该是

if(oper.equals("add") || oper .equals("addition") || oper.equals("+")) {

使用.equals方法检查两个字符串是否有意义相等==运算符只检查两个引用变量是否引用同一个实例。

答案 4 :(得分:1)

请勿使用String==进行比较。请改用equals

答案 5 :(得分:1)

使用equals(..)而不是==

比较字符串

替换

if(oper == "add" || oper == "addition" || oper == "+") {

通过

if(oper.equals("add") || oper.equals("addition") || oper.equals("+")) {

==对同一参考进行比较,而不是相同内容。

答案 6 :(得分:1)

执行所有其他人的说法:使用equals甚至equalsIgnoreCase。 (在其他答案中对此有很好的解释。在这里重复它会很愚蠢。)

在没有“在控制台中”的情况下输入“添加”。

只做这两件事都可以。

答案 7 :(得分:0)

使用此

    if("add".equals(oper)  || "addition".equals(oper) || "+".equals(oper)) {
double sum = num1 + num2;
        System.out.printf("The sum of the two numbers is %d", sum);
    }

答案 8 :(得分:0)

除了使用equals()或更好equalsIgnore()代替==字符串外,您还需要在add而不是command-line中输入"add" {1}}。

否则,您必须将其比较为:

oper.equals("\"add\"")

此外,您似乎来自C背景。通常在Java中,可以使用:

System.out.println("The sum of the two numbers is " + sum);

而不是

System.out.printf("The sum of the two numbers is %d", sum);

因为%d打印integer值和not double值。

相关问题