4

So im still trying to make this calculator work correctly. The whole point is for it to keep asking for a y value and an operator until the user inputs "q". The only thing is that it wont return the value and it wont stop once i input q. It just keeps asking for a y value afterwards. Heres an example of the output i keep getting. Do i have to create an extra variable to hold the y value to update it and print it out afterwards?

X: 5 Y: 5 Op: + Y: 5 Op: q Y:

    Scanner keyboard = new Scanner(System.in);

    double x;
    double y;
    String Op;

    System.out.print("X: ");
    x = keyboard.nextDouble();

    do{
        System.out.print("Y: ");
        y = keyboard.nextDouble();
        keyboard.nextLine();
        System.out.print("Op: ");
        Op = keyboard.nextLine();

        if(Op == "+"){
            double result = sum(x,y);
            System.out.println(result);
            }
        else if(Op == "/"){
            double division = div(x,y);
            System.out.println(division);
            }
        else if(Op == "-"){
            double subtraction = sub(x,y);
            System.out.println(subtraction);
            }
        else if(Op == "*"){
            double times = mult(x,y);
            System.out.println(times);
            }
        else if(Op == "q")
            System.out.print("Your last result was: " +y);
    }while(Op != "q");

}   
public static double sum (double a, double b){
    double res = a + b;
    return res;
}
public static double div (double a, double b){
    if(b==0){
        System.out.println("Error, attempted a division by zero");
        return b;
        }
    double divide = a/b;
    return divide;
}
public static double sub (double a, double b){
    double minus = a-b;
    return minus;
}
public static double mult (double a, double b){
    double times = a*b;
    return times;
}

}

Squash
  • 89
  • 1
  • 5

2 Answers2

1

For String comparisons you need to use the method equals or equalsIgnoreCase.

The == operator will only work for primitives such as char,int, byte, etc. For objects, such as String, you need to use comparison methods.

Converting to the correct method will fix your problems. Example

if (Op.equalsIgnoreCase("q")){
    ...
}
greedybuddha
  • 7,488
  • 3
  • 36
  • 50
0

The == and != operators do not work for strings. You have to use Op.equals("...") instead.

benestar
  • 552
  • 4
  • 12