0

I am new to Java and I am creating a simple calculator. I used while loop to run it continuously but I couldn't stop it, Please help me with the code.

My calculator class code is:

package calculator;

import java.util.Scanner;

public class Calculator {

    public static void main(String[] args) {
        Boolean keepRunning = true;
        while (keepRunning) {
            double a, b, out;
            int n;
            String ans = null;
            Scanner in = new Scanner(System.in);
            System.out.println("Enter two Numbers ");
            a = in.nextDouble();
            b = in.nextDouble();

            System.out.println("Enter the mode of operation:" + "\n"
                    + "1. Addition" + "\n"
                    + "2. Subtraction" + "\n"
                    + "3. Multiplication" + "\n"
                    + "4. Division");
            n = in.nextInt();
            switch(n){
                case 1:
                    out = add(a,b);
                    System.out.println("The output is: "+ out );
                    break;
                case 2:
                    out = sub(a,b);
                    System.out.println("The output is: "+ out );
                    break;
                case 3:
                    out = mul(a,b);
                    System.out.println("The output is: "+ out );
                    break;
                case 4:
                    out = div(a,b);
                    System.out.println("The output is: "+ out );
                    break;
                default:
                    System.out.println("Enter Valid option");
                    break;                
            }
            System.out.println("Do you want to continue? (Y/N)");
            Scanner in1 = new Scanner(System.in);
            ans = in1.next();

            if(ans == "Y" || ans == "y"){

            }else if(ans == "N" || ans == "n"){
                keepRunning = false;    
                System.exit(0);
            }        
        }      
    }

    public static double add(double a, double b){
        return a+b;
    }
    public static double sub(double a, double b){
        return a-b;
    }
    public static double mul(double a, double b){
        return a*b;
    }
    public static double div(double a, double b){
        return a/b;
    }
}

The if loop is not at all running what's the problem in it.

Note: This question is already exist in Stackoverflow but I can't find my answer.

Aravind Ekan
  • 27
  • 1
  • 6

1 Answers1

1

Don't compare strings with == in Java, use "N".equals(ans), for example. Look out to the duplicate that @EJP post for you

developer_hatch
  • 15,898
  • 3
  • 42
  • 75