如何重复代码;如果用户输入没有。我想要重复所有三个循环,直到用户输入是

时间:2015-10-10 02:42:13

标签: java while-loop repeat

// First loop for number of quarters
int quarter;
while (true) {
    System.out.print("Enter number of quarters (1-10): ");
    if (keyboard.hasNextInt() && (quarter = keyboard.nextInt()) >= 1 && quarter <= 10)
        break;

    keyboard.nextLine(); // Discard bad input
    System.out.println("Number of quarters must be between 1 and 10");
}
keyboard.nextLine(); // Discard rest of line
System.out.println("You have " + quarter + " quarters.");
// Second loop for the rate of intrest
double intrestRate;
while (true) {
    System.out.print("Enter interest rate (5%-25%), without percent sign: ");
    if (keyboard.hasNextDouble() && (intrestRate = keyboard.nextDouble())  >= 5 && intrestRate <= 25)
        break;

    keyboard.nextLine(); // Discard bad input
    System.out.println("Interest rate must be between 5% and 25%");
}
keyboard.nextLine(); // Discard rest of line
System.out.println("You have selected a " + intrestRate + "% rate of  interest.");

// Third loop
double balance;
while (true) {
    System.out.print("Enter beginning principal balance, that is greater than zero: $");
    if (keyboard.hasNextDouble() && (balance = keyboard.nextDouble()) > 0);
        break;
}

好吧假设,此时,还有另一个分支询问上面的*输入是否正确,输入Y表示是,或N表示否。如果输入Y,我可以很容易地得到代码中断。但是,如果用户在N(IgnoreCase)中输入整个分支再次启动的话,我该怎么做呢?因此,如果用户输入否。程序将重复,循环1到循环3,直到它们满足为止。 (循环显示在//代码中。

1 个答案:

答案 0 :(得分:0)

我不确定您在代码方面提出的要求,但一般来说,如果答案为“否”,则重新启动部分代码的方法是放置代码段在一个循环中。

//initialize a String to "No"

while(user input is "No"){
     //your segment of code
System.out.println("Is this correct?");
// take user input by method of your choice. Yes will break out of loop, no will go back to start of while loop
}