1

I'm trying to create a calculator for one of my first projects in java. I ask the user for two number inputs and a symbol to choose the operation. It asks for the inputs then stops once it reaches the if statements to calculate the answer.

import java.util.Scanner;
class Calculator{

    public static void main(String args[]){
        double a;
        double b;
        double answer;
        String symbol;
        Scanner in = new Scanner(System.in);
        System.out.print("Enter an operation");
        symbol = in.nextLine();
        System.out.print("Enter the first number");
        a = in.nextInt();
        System.out.print("Enter the second number");
        b = in.nextInt();

        if (symbol == "+"){
            answer = a+b;
            System.out.print(answer);

        }
        else if (symbol == "-"){
            answer = a-b;
            System.out.print(answer);

        }
        else if (symbol == "/"){
            answer = a/b;
            System.out.print(answer);

        }
        else if (symbol == "*"){
            answer = a*b;
            System.out.print(answer);

        }
    }
}

Here is my output

Enter an operation +
Enter the first number 4
Enter the second number 5
  • 1
    `symbol == "*"` → `symbol.equals("*")` – Joop Eggen Dec 13 '17 at 08:31
  • Strings cannot be compared with "==" in java. Use symbol.equals("+"). Even better use "+".equals(symbol) – uday Dec 13 '17 at 08:31
  • 1
    One could use too: `switch (symbol) { ... case "*": answer = a*b; break; }` – Joop Eggen Dec 13 '17 at 08:33
  • Just another advice : use an `else` (or `default`in case of `switch`) and display a message telling that the operation is not recognized. This facilitates the diagnostic. – C.Champagne Dec 13 '17 at 08:46
  • As previous comment described you can not use "==" for Strings. Best way to do such operations use java.lang.Math class in java. Then you can simplify the code. – YAS_Bangamuwage Dec 13 '17 at 09:09

0 Answers0