【发布时间】:2013-01-26 03:24:43
【问题描述】:
大家好,我有一个有趣的问题。这是我学习面向对象编程的第二个学期。我在 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);
}
【问题讨论】:
-
readDate()是做什么的? -
为什么要在这里将声明与定义分开?
String[] a = dateString.split(" ");读起来好多了。 -
readDate();从用户那里读取一个字符串,并且仅在其内容是纯整数时才返回该字符串
-
@EverMartinez - 好吧,您没有将
readDate()的返回值分配给变量,所以这是一个问题。
标签: java arrays string date split