user2620255 user2620255 - 6 months ago 14
Java Question

java calculator loop not working properly

For some reason my calculator won't wait for user input to finish the do while loop. I'm very new to java coding (currently only been doing it for a few hours). I want the user to be able to do more math before the program closes instead of having to reopen it every time they want to use it (obviously I don't mean anything serious by this I just want to learn and I think this will help.

heres my code

import java.util.Scanner;


public class calculator {
public static void main(String[] args){
double Answer;
String op;
double num1;
double num2;
String again;
boolean yesorno = true;

Scanner input = new Scanner(System.in);

while (yesorno = true){
System.out.print("What opperation would you like to preform? +,-,*,/, :");
op = input.nextLine();
System.out.print("What is the first number? : ");
num1 = input.nextDouble();
System.out.print("And the seccond number? : ");
num2 = input.nextDouble();
if (op.equals("+")) {
Answer = (num1 + num2);
System.out.println(Answer);

} else if (op.equals("-")) {
Answer = num1 - num2;
System.out.println(Answer);

} else if (op.equals("*")) {
Answer = num1 * num2;
System.out.println(Answer);

} else if (op.equals("/")) {
Answer = num1 / num2;
System.out.println(Answer);

}
System.out.println("Would you like to do any more math?");
again = input.nextLine();
if (again.equals("yes")) {
yesorno = true;
} else if (again.equals("no")) {
yesorno = false;
System.out.print("have a good day!");

}
} while (yesorno = true);
}
}


please ignore the akward formatting at the beggining and end of this code.

Answer

1) while(yesorno = true ) you are doing assignation change to while(yesorno == true) to prevent this thing you can use yoda style while(true = yesorno) then a compile error would throw cause you can't assign something to a value. Or even more simpler just use while(yesorno)

2) Follow Java Code Convention , variable names are in lower case.

3)if this block get executed while (yesorno = true); you will have an infinite loop.

4) If you are using java 7 , you can do switch over strings

             switch(op){
             case "+":answer = num1 + num2;break;
             case "-":answer = num1 - num2;break;
             case "*":answer = num1 * num2;break;
             case "/":answer = num1 / num2;break;
             default: throw new IllegalArgumentException("Invalid operation "+ op);
             }
             System.out.println(answer);
Comments