【发布时间】:2017-11-08 20:25:33
【问题描述】:
public void askForDate(Scanner in) {
System.out.println("Please enter the date that the vehicle entered the car park in this format dd/mm/yyyy :");
String enteredDate = in.nextLine();
//This array will hold the 3 elements of which the date is made up of, day, month and year, and this method returns it.
String[] dateEnteredSplit = enteredDate.split("/");
//I am using the split method to seperate each number, which returns an array, so I am assigning that array to the dateEnteredSplit array.
//dateEnteredSplit = enteredDate.split("/");
//So now the first element holds the day, second the month, and the third element holds the year.
//System.out.println(Arrays.toString(dateEnteredSplit));
//Assigning each element and converting them to integers.
int day = Integer.parseInt(dateEnteredSplit[0]);
int month = Integer.parseInt(dateEnteredSplit[1]);
int year = Integer.parseInt(dateEnteredSplit[2]);
**System.out.println("day: " + day + " month: " + month + " year: " + year);**
//The loop will be entered if any of the values are wrong. which will use recursion to call this method again for a chance to enter the date again.
while (!(day >= 1 && day <= 31) || !(month >= 1 && month <= 12) || !(year > 1000 && year < 5000)) {
**System.out.println("day: " + day + " month: " + month + " year: " + year);**
//Im calling these methods to inform which one specifially was wrong so they know what they need to change.
this.setDay(day);
this.setMonth(month);
this.setYear(year);
dateEnteredSplit[0] = "0";
askForDate(in);
}
//I then assign any correct value into the object attribute because the while loop is either finished or not entered at all.
//No need to use setDay etc. here because the checks have been done above in the while loop.
this.day = day;
this.month = month;
this.year = year;
}
好的,这是一个类中的方法。它要求输入格式为 dd/mm/yyyy
如果我第一次输入 1996 年 12 月 1 日,它可以工作,但如果我首先输入错误的日期,例如 123/123/123,然后输入正确的日期,例如 1996 年 12 月 1 日,它仍然进入循环。
调试后,第一行加粗的值与第二行加粗的值不同,好像值是自己变化的。
这里有什么问题?过去 1 小时内我一直在尝试找出答案。
提前致谢!
【问题讨论】:
-
看起来这是因为递归。一旦他们输入正确的值,您的函数就会结束调用,然后一旦您返回上一个方法,就会分配旧值。一种肮脏的方法是,将正确的值返回给先前的函数调用
-
不要使用递归处理无效输入,而是使用循环(请求输入直到输入有效)。使用递归只会产生问题和混淆代码。
标签: java variables random methods