有人可以解释一下这段代码有什么问题吗?

时间:2014-02-25 14:14:36

标签: java

该程序执行以下操作: 第一个输入从用户获得两个数字,第二个输入如果用户输入(+)符号,程序将两个数字相加,如果用户输入( - )符号,则从第二个数字中减去第一个数字。 但没有结果显示该程序只是运行和终止。

import javax.swing.JOptionPane;

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

    String strNum1 = JOptionPane.showInputDialog("Enter the first number");
    String strNum2 = JOptionPane.showInputDialog("Enter the second number");

    int num1 = Integer.parseInt(strNum1);
    int num2 = Integer.parseInt(strNum2);

    String askForOperation = JOptionPane.showInputDialog("What operation needs to be done?");

    int sum;
    if (askForOperation == "+") {
            sum = num1 + num2;
            JOptionPane.showMessageDialog(null, "The result of the Addition is " + sum);
    }

    double subtract;
    if (askForOperation == "-") {
            subtract = num2 - num1;
            JOptionPane.showMessageDialog(null, "The result of the subtraction is " + subtract);

    }



    }

}

6 个答案:

答案 0 :(得分:6)

if (askForOperation == "+")  // Reference is not same

使用equals方法进行比较检查。

if ("+".equals(askForOperation))  // Compare content

答案 1 :(得分:1)

试试这个

if (askForOperation.equals("+")) {
        sum = num1 + num2;
        JOptionPane.showMessageDialog(null,
                   "The result of the Addition is " + sum);
}

要避免任何Nullpointer异常,无论如何

这样做,

final String plus = "+";
if (plus.equals(askForOperation)) {
        sum = num1 + num2;
        JOptionPane.showMessageDialog(null,
                   "The result of the Addition is " + sum);
}

答案 2 :(得分:1)

这个测试:

askForOperation == "+"

错了。做的是比较askForOperation和(无名)字符串"+"引用,它们完全不相同。

你想要比较内容;因此你必须使用:

"+".equals(askForOperation)

“ - ”相同。

样品:

String h1 = "hello";
String h2 = new String("hello");
h1 == h1; // true: same reference
h1 == h2; // false: different reference
h1.equals(h2); // true: same contents

请注意,由于字符串文字,字符串有点特殊 - "+"将“静默”为您创建String对象,这就是为什么您可以编写“看起来很奇怪”的代码,例如"foo".equals(bar)

答案 3 :(得分:0)

if(askForOperation.equals("+"){
    do smth..
}

使用== for String是错误的,你必须比较像String1.equals(String2);

这样的内容

答案 4 :(得分:0)

尝试

    .equals

方法而不是==

==比较对象引用,.equals比较对象值的值。

答案 5 :(得分:0)

相关问题