如何重复某些操作,直到在Java中给出正确的输入? [英] How to repeat something until correct input is given in java?

查看:168
本文介绍了如何重复某些操作,直到在Java中给出正确的输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个应用程序,对于该应用程序的一部分,我需要从用户那里获得输入,说明在1秒钟内单击鼠标的次数。我希望输入的数字介于1到10之间,以及其他任何给定的数字,例如0,-1、11为他们提供一个错误,并要求他们输入1-10的有效数字。同样,如果用户键入任何字符,例如名称(A,Jo或hello),以向他们提供错误信息并要求他们提供正确的输入。以下是我所拥有的,但它不起作用。

I am trying to make a application and for one part of the application I need to get a input from the user stating how many times there click their mouse in 1 second. I want the input their give to be between 1-10 and any other number given e.g. 0, -1, 11 to provide them with a error and ask them to input a valid number of 1-10. Also if the user types in any character e.g. name, A, Jo or hello, to also provide them with a error and ask them to provide the correct input. Below is what I have but it does not work.

    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,你好,因为我不确定我该怎么做,有人可以告诉我。

I haven't yet implemented not to accept any characters like name, j, A, hello because I am not sure how I can do this, can someone show me please.

编辑:
int mouseClick;

edit: 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);


推荐答案

所要求的示例:

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

这篇关于如何重复某些操作,直到在Java中给出正确的输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆