How to repeat something until correct input is given in java?

后端 未结 2 1575
野趣味
野趣味 2021-01-26 00:58

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

相关标签:
2条回答
  • 2021-01-26 01:23

    Use do while loop instead of while loop. This lets you run the loop atleast once before it tests the condition, where you can test the input.

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

    Example:

     Scanner input= new Scanner(System.in);
     do {
        System.out.println("Please enter the advertising cost: ");
        advertCost = input.nextDouble();
    
        } while (advertCost >= 100000 || advertCost <= 900000);
    

    I have added link on how to validate inputs

    Hope this helps!

    0 讨论(0)
  • 2021-01-26 01:40

    An example as requested:

    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);
    
    0 讨论(0)
提交回复
热议问题