0

Iam making a basic calculator with 3 functions. Iam using a Scanner-utility to help me interact with the calculator. You enter the first number, then it saves it to a variable, You enter a second number and that is also saved to a variable. Then after that it asks you what you want to do with the numbers. You can choose between Multiply, Add, Subtract. But none of them seem to work, and i dont know why, but iam guessing that the String that is inserted after the question isnt saved or maybe iam using wrong method.

import java.util.Scanner;

public class MainClass {




private static final String Multiply = null;
    private static final String Add = null;
    private static final String Subtract = null;

    public static void main(String[] args)
    {
        MainClass mainObject=new MainClass();
        mainObject.Calculator();




    }

    public void Calculator()
    {
        double firstnumber;
        double secondnumber;
        double result;
        String word1="Multiply";
        String word2="Add";
        String word3="Subtract";

        Scanner scan=new Scanner(System.in);
        System.out.println("Enter first number");
        firstnumber=scan.nextInt();
        System.out.println("Enter second number");
        secondnumber=scan.nextInt();
        System.out.println("What do you want to do?");
        String operator=scan.next();

        if(operator==word1)
        {
            result=firstnumber*secondnumber;
            System.out.println(result);


        }
        else if(operator==word2)
        {
            result=firstnumber+secondnumber;
            System.out.println(result);
        }
        else if(operator==word3)
        {
            result=firstnumber-secondnumber;
            System.out.println(result);
        }
    }
}
flo
  • 9,713
  • 6
  • 25
  • 41
Genesis
  • 55
  • 3
  • 13

1 Answers1

1

The comparison operation between the strings is not == but the equals() method:

if(operator.equals("add"))
    ...
else if (operator.equals("subtract"))
    ...
else if (operator.equals("multiply"))
    ...
else
    wrong input
Giulio Biagini
  • 935
  • 5
  • 8