I am wondering how I could make this code loop whenever the user gives a number outside of what the operator variable is asking. I am open to different suggestions. I have tried and failed many times using the do while loop. I want the code to say "Choose a number between 1-4" if the user gives the wrong number and then I want the loop back to the operator variable until the user gives a correct number and after the correct answer is given I want the program to go though the rest of the code and close.
import static java.lang.System.*;
import static javax.swing.JOptionPane.*;
import static java.lang.Integer.*;
public class SimpleCalc {
public static void main(String[] args) {
do {
String operator = showInputDialog("Choose operation: " + "\n" +
"[1] = Plus" + "\n" +
"[2] = Minus" + "\n" +
"[3] = Multiply" + "\n" +
"[4] = Divide" + "\n");
int c = parseInt(operator);
if (c>4 || c<1) {
showMessageDialog(null, "Choose a number between 1 - 4.");
}
else{
String textA = showInputDialog("Enter first number: ");
String textB = showInputDialog("Enter second number: ");
int a = parseInt(textA);
int b = parseInt(textB);
switch(c) {
case 1:
showMessageDialog(null, a + " + " + b + " = " + (a+b));
break;
case 2:
showMessageDialog(null, a + " - " + b + " = " + (a-b));
break;
case 3:
showMessageDialog(null, a + " * " + b + " = " + (a*b));
break;
case 4:
showMessageDialog(null, a + " / " + b + " = " + (a/b));
break;
}
}
} while (c>4 || c<1);
}
}
You are on the right track by using do while loop. However the value c is not seen as its within the do while block. if you add int c
above the do block and make int c = parseInt(operator);
to c = parseInt(operator);
it will work
Move the declaration of c
out of do
block, otherwise it is not accessible in while
int c;
do {
...
c = parseInt(operator);
...
} while (c > 4 || c < 1);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.