【问题标题】:Array.length; is correct [closed]数组长度;是正确的[关闭]
【发布时间】: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


【解决方案1】:

您的函数 setDateFields 始终使用您传入的第一个字符串。您需要从用户那里获取另一个字符串(我认为 readDate() 会这样做,但它不能修改 setDateFields() 中的任何内容)。

您的主行代码应如下所示:

 do {
   dateString = readDate();
} while(!checkDateString(dateString));

checkDateString() 应该只检查传入的字符串并返回 true 或 false。

【讨论】:

  • 是的,当我声明我必须发布以前的版本时,我确实定义了它。我确实看到我的 readDate();方法没有修改任何东西..我会修改看看是否有帮助
猜你喜欢
  • 2011-03-17
  • 1970-01-01
  • 2019-04-23
  • 1970-01-01
  • 1970-01-01
  • 2011-09-30
  • 2017-08-26
  • 2019-12-17
  • 2021-12-03
相关资源
最近更新 更多