-1

I am new to Java and I am trying to code a calculator. The numbers are not calculating and I am not sure why that is happening.

Here is my code:

import java.util.Scanner;

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

        System.out.println("Type in any 2 numbers: ");
        Scanner math = new Scanner(System.in);
        int number = math.nextInt();
        int num2 = math.nextInt();

        System.out.println("Which operation would you like to use? (+,-,*,/)");
        String oper = math.next();

        if (oper == "+"){
            int total = number + num2;
            System.out.println(total);
        }
        else if (oper == "-"){
            int total = number - num2;
            System.out.println(total);
        }
        else if (oper == "*"){
            int total = number * num2;
            System.out.println(total);
        }
        else if (oper == "/"){
            int total = number / num2;
            System.out.println(total);
        }
    }

}
Ubermench
  • 3
  • 1
  • 4

2 Answers2

1

you should use the equals method in Java to compare strings. when you use "==" in classes it compare only refrences but not values. This should work with this fix

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

        System.out.println("Type in any 2 numbers: ");
        Scanner math = new Scanner(System.in);
        int number = math.nextInt();
        int num2 = math.nextInt();

        System.out.println("Which operation would you like to use? (+,-,*,/)");
        String oper = math.next();

        if (oper.equals("+")){
            int total = number + num2;
            System.out.println(total);
        }
        else if (oper.equals("-")){
            int total = number - num2;
            System.out.println(total);
        }
        else if (oper.equals("*")){
            int total = number * num2;
            System.out.println(total);
        }
        else if (oper.equals("/")){
            int total = number / num2;
            System.out.println(total);
        }
    }
Ran Koretzki
  • 464
  • 3
  • 15
0

@Ran Koretzki is right and i have one possible improvement for your code. You are reading input from user and assigning to "integer" values. Even if this code don't prompt any compile time or runtime error, there is a logical problem in your code.

You are dividing two integer and assigning the result to an integer. This approach works well when you try to divide two integer and if there is no remainder. But if there is a remainder in dividing process, you will lose this remainder or fraction. In order to solve that, you should read your input into double values and assign the operations result into double varaible.

ffguven
  • 187
  • 11