如何重复一些东西,直到在java中给出正确的输入?

时间:2014-01-19 11:06:30

标签: java eclipse input

我正在尝试创建一个应用程序,对于应用程序的一部分,我需要从用户那里获得一个输入,说明在1秒内点击鼠标的次数。我希望他们给出的输入介于1-10和任何其他数字之间,例如0,-1,11为它们提供错误并要求它们输入有效数字1-10。此外,如果用户输入任何字符,例如name,A,Jo或hello,也为他们提供错误并要求他们提供正确的输入。以下是我所拥有但不起作用。

    int OrginalMouseClick;

    String Mouseclick = JOptionPane.showInputDialog("Write down how many times you can click your mouse button in 1 second");
    int Mouseclick2 = Integer.parseInt(Mouseclick);

    while (Mouseclick2 < 1 || Mouseclick2 > 10) {
        String Mouseclick = JOptionPane.showInputDialog("Write down how many times you can click your mouse button in 1 second");   
         if (Mouseclick2 >= 1 || Mouseclick2 <10) {
             OrginalMouseClick = Mouseclick2;
             }
         }

我还没有实现不接受任何字符,如姓名,j,A,你好,因为我不知道我怎么能这样做,有人能告诉我。

编辑:         int mouseClick;

    do {
        while (!str.hasNextInt()) {
            String str = JOptionPane.showInputDialog("Write down how many times you can click your mouse button in 1 second");
            str.next(); // this is important!
        }
        String str = JOptionPane.showInputDialog("Write down how many times you can click your mouse button in 1 second");
        mouseclick = Integer.parseInt(str);
    }
    while (mouseclick < 1 || mouseclick > 10);

2 个答案:

答案 0 :(得分:0)

使用do while循环代替while循环。这使您可以在测试条件之前至少运行一次循环,在那里可以测试输入。

String input = null;
do {
    //get the input from user
} while (isInputValid); //check input validity here

示例:

 Scanner input= new Scanner(System.in);
 do {
    System.out.println("Please enter the advertising cost: ");
    advertCost = input.nextDouble();

    } while (advertCost >= 100000 || advertCost <= 900000);

我已就如何验证输入

添加了link

希望这有帮助!

答案 1 :(得分:0)

请求的示例:

int mouseClick;

do {
    String str = JOptionPane.showInputDialog("Write down how many times you can click your mouse button in 1 second");
    mouseclick = Integer.parseInt(str);
}
while (mouseclick < 1 || mouseclick > 10);