【问题标题】:Customs toString in Java not giving desired output and throwing errorJava中的自定义toString没有提供所需的输出并抛出错误
【发布时间】:2013-11-21 13:23:29
【问题描述】:

我正在用 Java 编写一个程序来根据公历接受和验证日期。我的 public boolean setDate(String aDate) 函数输入不正确,假设将 boolean goodDate 变量更改为 false。假设该变量告诉 toString 函数在调用时输出“无效条目”,但它没有。我的 public boolean setDate(int d, int m, int y) 函数工作正常。我只将问题部分作为一段很长的代码包含在内。谢谢

 public boolean setDate(int day, int month, int year){
    // If 1 <= day <= 31,  1 <= month <= 12, and 0 <= year <= 9999 & the day match with the month
    // then set object to this date and return true
    // Otherwise,return false (and do nothing)
    boolean correct = isTrueDate(day, month, year);
    if(correct){
      this.day = day;
      this.month = month;
      this.year = year;
      return true;
    }else{
      goodDate = false;
      return false;
    }
    //return false;
}

public boolean setDate(String aDate){
    // If aDate is of the form "dd/mm/yyyy" or "d/mm/yyyy" 
    // Then set the object to this date and return true.
    // Otherwise, return false (and do nothing)
    Date d = new Date(aDate);
    boolean correct = isTrueDate(d.day, d.month, d.year);
    if(correct){
      this.day = d.day;
      this.month = d.month;
      this.year = d.year;
      return true;
    }else{
      goodDate = false;
      return false;
    }
}

public String toString(){
    // outputs a String of the form "dd/mm/yyyy"
    // where dd must be 2 digits (with leading zero if needed)
    //       mm must be 2 digits (with leading zero if needed)
    //     yyyy must be 4 digits (with leading zeros if needed)
    String day1;
    String month1;
    String year1;
    if(day<10){
      day1 = "0" + Integer.toString(this.day);
    } else{
      day1 = Integer.toString(this.day);
    }
    if(month<10){
      month1 = "0" + Integer.toString(this.month);
    } else{
      month1 = Integer.toString(this.month);
    }
    if(year<10){
      year1 = "00" + Integer.toString(this.year);
    } else{
      year1 = Integer.toString(this.year);
    }
    if(goodDate){
    return day1 +"/" +month1 +"/" + year1;
    }else{
      goodDate = true;
      return "Invalid Entry";
    }

  }

谢谢

【问题讨论】:

    标签: java date boolean comparable


    【解决方案1】:

    此代码的一个主要问题是您的toString() 函数修改了程序的状态(通过将goodDate 设置为true)。问题是 toString 可以在您的代码中的任何地方被调用,即使您没有明确调用它。所以,我愿意打赌其他东西正在调用它并将goodDate 设置为true。看看你能不能找到一种方法让toString() 函数不改变状态。

    【讨论】:

      【解决方案2】:

      在第三方库Joda-Time 2.3 中更容易做到。在实例化一个新的DateTime 实例时,如果将无效值传递给构造函数,该类将引发异常。

      下面的代码利用了 Java 7 中的新 Multi-Catch Exceptions 功能。

      示例源代码:

      • 发票类,只是放置方法来尝试潜在的新日期时间有效性的地方。
      • 实例化发票然后调用有效性方法的其他代码。
      // © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
      
      public class Invoice {
      
          Boolean isDateTimeValid (int year, int month, int day) {
              org.joda.time.DateTimeZone losAngelesTimeZone = org.joda.time.DateTimeZone.forID("America/Los_Angeles");
              try {
                  org.joda.time.DateTime dt = new org.joda.time.DateTime(year, month, day, 0, 0, losAngelesTimeZone);
                  return true; // No exception thrown, so this must be a valid date-time.
              } catch (org.joda.time.IllegalFieldValueException e) {
                  return false; // Oops, invalid values used as input.
              } catch ( Exception e) {
                  System.out.println("ERROR Encountered an unexpected Exception: " + e.getStackTrace() );
                  return false;
              }
          }
      
      }
      

      在任何地方编写代码以调用该有效性方法。

      Invoice invoice = new Invoice();
      System.out.println( "Is valid date for 2013, 11, 15: " + invoice.isDateTimeValid(2013, 11, 15) );
      System.out.println( "Is valid date for 2013, 99, 15: " + invoice.isDateTimeValid(2013, 99, 15) );
      

      运行时……

      Is valid date for 2013, 11, 15: true
      Is valid date for 2013, 99, 15: false
      

      关于 Joda-Time 及相关问题……

      // Joda-Time - The popular alternative to Sun/Oracle's notoriously bad date, time, and calendar classes bundled with Java 7 and earlier.
      // http://www.joda.org/joda-time/
      
      // Joda-Time will become outmoded by the JSR 310 Date and Time API introduced in Java 8.
      // JSR 310 was inspired by Joda-Time but is not directly based on it.
      // http://jcp.org/en/jsr/detail?id=310
      
      // By default, Joda-Time produces strings in the standard ISO 8601 format.
      // https://en.wikipedia.org/wiki/ISO_8601
      
      // About Daylight Saving Time (DST): https://en.wikipedia.org/wiki/Daylight_saving_time
      
      // Time Zone list: http://joda-time.sourceforge.net/timezones.html
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-01-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-06
        • 1970-01-01
        • 2019-11-26
        相关资源
        最近更新 更多