如何为此添加do-while语句?

时间:2014-04-05 22:57:37

标签: java while-loop do-while

我需要让它重复询问用户是否有1到10之间的数字,但是当输入任何数字时它会终止。

import javax.swing.*;

public class Demo {
    public static void main (String [] args) {

       int n;

       n = Integer.parseInt(
               JOptionPane.showInputDialog(null,
                       "Enter a number between 1 and 10"));

       while (n < 1 && n > 10) {
               JOptionPane.showMessageDialog(null,"Your number is not between 1 and 10");
               n = Integer.parseInt(
                       JOptionPane.showInputDialog(null,
                               "Enter a number between 1 and 10"));
       }

       JOptionPane.showMessageDialog(null, "Good!\nClick OK to exit");
       System.exit(0);
   }
}

4 个答案:

答案 0 :(得分:4)

AND更改为OR

while (n < 1 || n > 10) { ... }

...并考虑将其转换为do-while循环的可能性,因为您必须至少显示一次该提示。

int n;
do {
   n = Integer.parseInt(JOptionPane.showInputDialog(null,
       "Enter a number between 1 and 10"));
   if (n >= 1 && n <= 10) {
     break;
   }
   JOptionPane.showMessageDialog(null,"Your number is not between 1 and 10");
} while (true);

// do something useful with n, will you? )

答案 1 :(得分:1)

如果你想无限循环,那么我建议使用while(true)然后使用break语句(在这种情况下你不需要休息,因为你调用System.exit(0)) - 这通常是然后尝试编写正确的whiledo while循环代码。

while(true){
    final int n = Integer.parseInt(JOptionPane.showInputDialog(null,
                    "Enter a number between 1 and 10"));
    if(n >= 1 && n <= 10){
        JOptionPane.showMessageDialog(null, "Good!\nClick OK to exit");
        System.exit(0);
    }
    // else continue loop
    JOptionPane.showMessageDialog(null,"Your number is not between 1 and 10");
}

或者这可能是:

while(true){
    final int n = Integer.parseInt(JOptionPane.showInputDialog(null,
                    "Enter a number between 1 and 10"));
    if(n >= 1 && n <= 10)
        break;
    // else continue loop
    JOptionPane.showMessageDialog(null,"Your number is not between 1 and 10");
}
JOptionPane.showMessageDialog(null, "Good!\nClick OK to exit");
System.exit(0);

答案 2 :(得分:0)

这是因为你的程序缺乏适当的结构和逻辑实现。

由于您只想在输入的数字介于1和10之间时退出用户,因此正确的逻辑应为

boolean userWantsToExit = false;
while (!userWantsToExit) {
   //hey user set n ;
   int n = Integer.parseInt(
                    JOptionPane.showInputDialog(null,
                   "Enter a number between 1 and 10"));
   if(n >= 1 && n <= 10){
     //reached here , means user want's to exit
     userWantsToExit = true;
   }
}

答案 3 :(得分:-1)

使用(n <1 ^ n> 10)代替(n&lt; 1&amp; n&gt; 10&gt; 10) ..并保持你的代码原样!