否则如果计算器中出现语法错误

时间:2015-03-17 04:35:13

标签: java

我一直在尝试制作一个基本的计算器,但每次我使用if else时都会发生这种情况,它要么说我必须删除它,因为语法错误或绿色下划线的内容出现了,它说死代码。有人能帮助我吗?

import java.util.Scanner;

public class additionCalculator {

public static void main(String[] args) {
    int addresult;
    int subtractresult;
    int divideresult;
    int multiplyresult;

    String addition = null;
    String subtraction = null;
    String division = null;
    String multiplication = null;

    Scanner reader = new Scanner(System.in);
    System.out.println("Do you want to do subtraction, division, multiplication, or addition?");
    String i = reader.next();

    if(i == addition)   {
        Scanner additioncalc = new Scanner (System.in);
        System.out.println("Enter a number");
        int add1 = reader.nextInt();

        Scanner additioncalc2 = new Scanner (System.in);
        System.out.println("Enter another number");
        int add2 = reader.nextInt();

        addresult = add1 + add2;

        System.out.println("The sum is " +addresult);



    }   else if (i == multiplication) {
        Scanner multiplicationcalc = new Scanner (System.in);
        System.out.println("Enter a number");
        int multiply1 = reader.nextInt();

        Scanner multiplcationcalc2 = new Scanner (System.in);
        System.out.println("Enter another number");
        int multiply2 = reader.nextInt();

        multiplyresult = multiply1 * multiply2;

        System.out.println("The product is " +multiplyresult);

    } else if (i == division) {
        Scanner divisioncalc = new Scanner (System.in);
        System.out.println("Enter a number");
        int div1 = reader.nextInt();

        Scanner divisioncalc2 = new Scanner (System.in);
        System.out.println("Enter another number");
        int div2 = reader.nextInt();

        divideresult = div1 * div2;
        System.out.println("The product is " +divideresult);


    } else if (i == subtraction) {
        Scanner subtractioncalc = new Scanner (System.in);
        System.out.println("Enter a number");
        int subtract1 = reader.nextInt();

        Scanner subtractioncalc2 = new Scanner (System.in);
        System.out.println("Enter another number");
        int subtract2 = reader.nextInt();

        subtractresult = subtract1 - subtract2;
        System.out.println("The difference is " +subtractresult);
    }
}


// Addition calculator
// Scanner reader = new Scanner(System.in);
// System.out.println("Please enter a number.");        
// int i = reader.nextInt();
// Scanner reader2 = new Scanner(System.in);
// System.out.println("Please enter another number.");
// int j = reader2.nextInt();

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

}

1 个答案:

答案 0 :(得分:2)

您应该使用java.lang.String中的字符串比较函数。

注意:

==测试参考相等。

.equals()测试值的相等性。