0

I've been trying to make a basic calculator, but the thing is every time I use if else, it either says I have to remove it due to syntax error or the green underline thing shows up and it says dead code. Could someone help me?

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 Answers1

2

You should be using string comparison function from java.lang.String.

Note:

== tests for reference equality.

.equals() tests for value equality.