程序不会循环回直到正确

时间:2018-02-11 21:46:17

标签: java

/*Do method to continually ask for correct spelled day until it matches a valid input */
do {   
    System.out.print('\n' + "What is the current Day (Monday-Sunday): ");
    currentDay = stdIn.nextLine();
}while (!(currentDay.equals("Sunday") || currentDay.equals("Monday") || 
          currentDay.equals("Tuesday") || currentDay.equals("Wednesday") ||
          currentDay.equals("Thursday") || currentDay.equals("Friday") || 
          currentDay.equals("Saturday")));

if(!currentDay.equals(dayOfFlight)){
    System.out.println("Today isn't your day for a flight, keep cheching");
}

while (!currentDay.equals(dayOfFlight));

System.out.print("What is the current hour (Military time): ");
int currentHour = stdIn.nextInt();

int time = (hourOfFlight - currentHour);
System.out.println('\n' + "You have " + time + " hours to go.");

3 个答案:

答案 0 :(得分:1)

你的第二个while将无所事事或无限循环。

要检查这一点,您可以逐步调试调试器中的代码。

while (!currentDay.equals(dayOfFlight));

相同
while (!currentDay.equals(dayOfFlight)) {
   // nothing changes so loop forever
}

你可能想要的是有一个第二个do/while循环,这就是结束。

答案 1 :(得分:0)

看看你的第二个while

while (!currentDay.equals(dayOfFlight));

就像Peter Lawyrey所说的那样,"你可能想要第二个do / while循环,这就是结束"。第二个do / while的开头很可能在第一个之外,因此封装第一个并执行它直到currentDay.equals(dayOfFlight)返回true:

do { // Beginning
    do {
        System.out.print('\n' + "What is the current Day (Monday-Sunday): ");
        currentDay = stdIn.nextLine();
    } while (!(currentDay.equals("Sunday") || currentDay.equals("Monday") || currentDay.equals("Tuesday")
            || currentDay.equals("Wednesday") || currentDay.equals("Thursday") || currentDay.equals("Friday")
            || currentDay.equals("Saturday")));

    if (!currentDay.equals(dayOfFlight)) {
        System.out.println("Today isn't your day for a flight, keep cheching");
        // Don't you mean "keep checking"?
    }

} while (!currentDay.equals(dayOfFlight)); // End

System.out.print("What is the current hour (Military time): ");
int currentHour = stdIn.nextInt();

int time = (hourOfFlight - currentHour);
System.out.println('\n' + "You have " + time + " hours to go.");

在旁注中,您可能希望将currentDay#equals更改为currentDay#equalsIgnoreCase,将System#print更改为System#println

答案 2 :(得分:0)

Scanner reader = new Scanner(System.in);
    String currentDay,dayOfFlight="Monday";
    int hourOfFlight=10;
    do {   
         System.out.print('\n' + "What is the current Day (Monday-Sunday): ");
         currentDay = reader.nextLine();


        if(!currentDay.equals(dayOfFlight)){
          System.out.println("Today isn't your day for a flight, keep cheching");
         }
    }

    while (!currentDay.equals(dayOfFlight));

        System.out.print("What is the current hour (Military time): ");
        int currentHour = reader.nextInt();

        int time = (hourOfFlight - currentHour);
        System.out.println('\n' + "You have " + time + " hours to go.");

您不需要使用while循环来检查直到正确。 (如果这是你想要达到的目标。)