如何为我的代码创建一个循环,以便它运行直到用户提供正确的输入?

时间:2018-05-05 16:14:24

标签: java

我想知道每当用户给出一个数字超出操作员变量要求的数字时,我怎么能做这个代码循环。我对不同的建议持开放态度。我尝试过多次使用do while循环失败了。我希望代码说“选择一个介于1-4之间的数字”,如果用户给出错误的数字,然后我希望循环回到操作员变量,直到用户给出正确的数字,并且在给出正确的答案之后,我想要程序通过其余代码并关闭。

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);
 }
}

2 个答案:

答案 0 :(得分:0)

使用do while循环你是在正确的轨道上。但是,值c不会被视为在do while块中。如果您在do块上方添加int c并将int c = parseInt(operator);添加到c = parseInt(operator);,则可以使用

答案 1 :(得分:0)

c的声明移出do阻止,否则while无法访问

int c;

do {
        ...

        c = parseInt(operator);

        ...
} while (c > 4 || c < 1);