大家好,我有一个有趣的问题。这是我学习面向对象编程的第二个学期。我在 Java 入门课程中的第一个项目涉及创建一个 Date 类,该类会计算从当年 1 月 1 日起经过的天数。我显然必须检查闰年并验证不正确的输入。我目前正在尝试检查用户输入的元素是否太少或太多(在一个字符串中)。这就是我所拥有的,但逻辑在某处存在缺陷。当我输入的元素太少时,它会显示错误并再次读取。然后我输入太多它会显示错误并再次读取。然后,当我输入三个元素时,它会显示上一个错误。在一个错误之后,它不接受只输入了 3 个元素。请帮忙。
/* Accepts a string as an argument and splits it into 3 sections
* month,day, and year
*/
void setDateFields(String dateString){
String [] a = {null}; // Array created to hold dateString
a = dateString.split(" "); // Split dateString into three sections
// each ending with a white space
// While to check if user entered month day and year
while (a.length != 3){
if(a.length < 3)
System.out.println("Insufficient number of elements\n" +
"Enter a new date in the format of MM DD YYYY");
else if(a.length > 3)
System.out.println("Too many elements entered\n" +
"Enter a new date in the format of MM DD YYYY");
readDate();
a = dateString.split(" ");
}
monthText = a[0]; // The monthText is assigned the first index of the array
dayText = a[1]; // The dayText is assigned the second index of the array
yearText = a[2]; // The yearText is assigned the third index of the array4
numericMonth = Integer.valueOf(monthText);
numericDay = Integer.valueOf(dayText);
numericYear = Integer.valueOf(yearText);
}