2

I am trying to do a while loop but it kept failing on me. So while date is not entered by the user, this will keep running until a valid date is entered. isValidDate is a method to check whether the date is true or false. Date will only be true when enter dd/mm/yy.

I am trying to put a check on whether the date is correct or not. If it is correct, it will be stored into the String date and the program will continue. If it is incorrect, the program will then prompt the user again for the correct date.

When I first enter a incorrect date, it will then prompt me for the correct date to be entered again. At this point, when I enter a correct date, the program could not verify if it is a correct date or not anymore. Why is this happening?

Please help!

    public void bookingA(){
        bkList = new ArrayList<bookingInfo>();

        Scanner keys = new Scanner(System.in);
        String date;

        System.out.println("\nEnter the date: ");
        while(!isValidDate(keys.nextLine())) {
            do {
               System.out.println("That is not a valid date! Please enter again (dd/mm/yy): ");
               date = keys.nextLine();
            } while (!isValidDate(date));
            System.out.print(date);
            break;
        }
}
4

2 回答 2

3

你在那里有无限循环,将其更改为:

System.out.println("\nEnter the date (dd/mm/yy): ");
while (true) {
    date = keys.nextLine();
    if (isValidDate(date)) {
         break;
    } else {
         System.out.println("That is not a valid date! Please enter again (dd/mm/yy): ");
    }
} 
System.out.print(date);
于 2013-04-14T10:44:20.627 回答
0

每个都keys.nextLine需要另一个输入。您必须将输入读入一次变量,然后引用该变量!因为你正在每个内循环读取输入三遍。

根据您编辑后的代码进行编辑,仍然存在问题。您仍然有两个地方可以读取输入 - 在 while 循环和条件中。当您只需要一个时,您仍然有两个 while 循环。我删除了几行,并date在循环开始之前添加了一个初始分配。这让你:

public void bookingA(){
    bkList = new ArrayList<bookingInfo>();

    Scanner keys = new Scanner(System.in);
    String date;

    System.out.println("\nEnter the date: ");
    date = keys.nextLine();
    while(!isValidDate(date)) {
        System.out.println("That is not a valid date! Please enter again (dd/mm/yy): ");
        date = keys.nextLine();
    }
    System.out.print(date);

注意 - 我试图维护您的代码的一些结构(即while实际测试变化条件的 a )但 Milos 给出的答案(当日期有效时您会中断一个无限循环)可能是通常是更好的解决方案,因为您无需在输入日期之前将日期设置为某个值。另一方面,您可以说,在我建议的代码中,您的假设是用户输入了一个有效的日期,并且 while 循环在那里确认它,如果日期证明无效,则再给一次机会。

如您所见,两种解决方案都有效,但一种理念是“我将您置于此循环中,在您输入有效日期之前我不会让您出去”,而另一种解决方案是“我将继续检查您输入的日期是有效的,直到它是“。

但是两者都比您的原始代码更具可读性。一个简单的任务需要一个简单的代码结构。值得为之努力。

于 2013-04-14T10:46:02.823 回答