且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

重新提示用户在Java中输入有效输入

更新时间:2023-01-11 12:55:21

您可以使用do-while循环.

You can use a do-while loop.

do{
    //Some code here

    //if block
    else { // last else block.
         System.out.println("Invalid Membership");
         continue;  // This will skip the rest of the code and move again to the beginning of the while loop.
    }

    //More code

    break; // If the condition was correct, then you need not worry. This statement will pull out of the loop.
}while(true);

您可以对其进行修改,以在需要的任何地方放置一个do-while循环.

You can modify this to put a do-while loop any where you have such requirement.

这将使您的整个代码成为:

This would make your whole code to:

public static void main(String[] args) throws Exception
{

    InputStreamReader ui = new InputStreamReader (System.in);
    BufferedReader inputReader = new BufferedReader(ui);
    String membership, tyreRental,parking;
    double x = 0d;
    do
    {
        System.out.println("Select Membership Type: (Gold/Silver/Bronze)");
        membership = inputReader.readLine();

        if (membership.equals("Gold"))
            System.out.println("Gold Membership Selected: £" + (x = 750));
        else if (membership.equals("Silver"))
            System.out.println("Silver Membership Selected: £" + (x = 450));
        else if (membership.equals("Bronze"))
            System.out.println("Bronze Membership Selected: £" + (x = 250));
        else{
            System.out.println("Invalid Membership");
            continue;
        }
        break;
    }while(true);

    do{
        System.out.println("Do you require snow tyre rental? (yes/no)");
        tyreRental = inputReader.readLine();

        if (tyreRental.equals("yes"))
            System.out.println("The total so far with tyre rental: £" + (x = x * 1.1));
        else if (tyreRental.equals("no"))
            System.out.println("The total so far without tyre rental: £" + x);
        else{ System.out.println("Invalid response"); continue;}
        break;
    }while(true);

    do{
        System.out.println("Would you like to reserve parking? (yes/no)");
        parking = inputReader.readLine();

        if (parking.equals("yes"))
            System.out.println("Membership total: £" + (x = x * 1.08));
        else if (parking.equals("no"))
            System.out.println("Membership total: £" + x);
        else {System.out.println("Invalid response"); continue;}
        break;
    }while(true);
}