如果语句错误,Java

时间:2016-02-11 02:18:23

标签: java if-statement

import java.util.Scanner;

public class Assignment3 {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println("Welcome to the Calculator!");
        System.out.println("Enter the first operand:");
        double firstOperand = scan.nextDouble();
        System.out.println("Enter the second operand:");
        double secondOperand = scan.nextDouble();
        System.out.println("Operations are:");
        System.out.println("ADD or  + for addition");
        System.out.println("SUBTRACT or - for subraction");
        System.out.println("MULTIPLY or * for multiplication");
        System.out.println("DIVIDE or / for division");
        System.out.println("Enter your selection:");
        String selection = scan.next();
        double ADD = (firstOperand + secondOperand);
        double SUBTRACT = (firstOperand - secondOperand);
        double MULTIPLY = (firstOperand * secondOperand);
        double DIVIDE = (firstOperand / secondOperand);

        if (selection == ADD) {
            System.out.println("The product is:" + ADD);
        }
        if (selection == SUBTRACT) {
            System.out.println("The product is:" + SUBTRACT);
        }
        if (selection == MULTIPLY) {
            System.out.println("The product is:" + MULTIPLY);
        }
        if (selection == DIVIDE) {
            System.out.println("The product is:" + DIVIDE);
        }
    }
}

这是我为每个if语句得到的错误。

error: incomparable types: String and double
        if (selection == ADD)

我正在尝试创建一个简单的计算器,我不明白错误试图传达的是什么。我还想为一个定义分配两个变量,但我不知道如何去做,特别是+-符号。甚至可以将+符号指定为变量吗?例如,我希望+与我写ADD时的内容相同?

3 个答案:

答案 0 :(得分:3)

您正在将字符串与double进行比较。您需要将字符串与字符串进行比较。 试试这个:

Table: Users
ID123   John Doo
ID345   John Woo

Table: Contacts
ID123  Microsoft  johnd@microsoft.com  +1-234567
ID345  Private Co johnw@privateco.com  +9-654321 
ID345  IBM        johnw@ibm.com        +1-456789

答案 1 :(得分:0)

正如我们从错误消息中可以看到的,不同数据类型的原因。您可以使用Double.parseDouble()将String转换为double。

...
if (Double.parseDouble(selection) == ADD)
...

P / S:您应该将标记从JavaScript更改为Java。

答案 2 :(得分:0)

您可以通过更改变量的声明来修复它

Double selection = new Double(scan.next());