Java calculator does not display an answer

So I'm still trying to make this calculator right. The thing is that he continues to request the value of y and the operator until the user enters "q". The only thing is that it will not return a value, and it will not stop after entering q. It just keeps asking for the y value after that. Here is an example of the output I get. Do I have to create an additional variable to save the y value, to update it and subsequently print it?

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 = ab; return minus; } public static double mult (double a, double b){ double times = a*b; return times; } 

}

+4
source share
2 answers

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

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

Converting to the correct method will fix your problems. Example

 if (Op.equalsIgnoreCase("q")){ ... } 
+1
source

The == and! = Operators do not work for strings. Instead, you should use Op.equals ("...").

0
source

Source: https://habr.com/ru/post/1483439/


All Articles