0

これは宿題です。

目標: 2 つのオブジェクトの日付を比較して、人物オブジェクトが成人かどうかを判断し、これを文字列に格納したいと考えています。

奇妙なことに、日付 d1 の値はすべて 0 です。

public class Date {

  public int day, month, year;  
  public String child

  Date(date d1, date d2) {
      if ((d1.year - d2.year > 18) ||
          ((d1.year  - d2.year == 18) && (d2.year> d1.year)) ||
          ((d1.year  - d2.year == 18) && (d2.year == d1.maand) && (d2.day > d1.day))) {
             child = adult;  
      } else {
            child = child;
  }

  Date(int a, int b, int c) {
    a = year;
    b = month; 
    c = day; 
  }

  Date (String birthdate) {
    String pattern = "\\d{2}-\\d{2}-\\d{4}";
    boolean b = birthdate.matches(pattern);
    if (b) {
        String[] str = birthdate.split("-"); 
        for (String s: str)
            this.day = Integer.parseInt(str[0]);
            this.month = Integer.parseInt(str[1]);
            this.year = Integer.parseInt(str[2]);
            this.child = false; 
    } else {
          System.out.println("Wrong format");
    } 

}

テストを行うと、次のことが起こります。

  System.out.println("D1 year = " + d1.year); 
  System.out.println("D1 day = " + d1.day); 
  System.out.println("D1 month = " + d1.month);
Result: 
D1 year = 0
D1 day = 0
D1 month = 0

なぜこれが起こるのですか?私の他のクラスを見てみましょう。

メソッド infoPerson が配置されている他のクラスは次のとおりです。

    public static Person infoPerson() {

       String name, lastname, birthdate;  
       Datum birthday, today;  

       System.out.println("Firstname:");
       name = userInput();  
       System.out.println("Lastname:");
       lastname = userInput(); 
       System.out.println("Birthdate?:");
       birthdate = userInput(); 

       //here I send the string birthdate to my Date class
       birthday = new Date(birthdate); 
       today = new Date(3, 7, 2013); 


      //Here I want to compare my two Date objects, today and birthday. This is were I got stuck, how do I do this correctly?
      dateChild = new Date(today, birthday); 

      // here i send the new date to my Person class what consists of two strings and Data birthday
      return new Gast(name, lastname, dateChild); 

   }
4

1 に答える 1

5

コンストラクターでの代入は逆になります。

Date(int a, int b, int c) {
    a = year;    // should be year = a;
    b = month;   // month = b;
    c = day;     // day = c;
}

Java API で定義されているものと同じクラス名を使用しないでください。Dateはすでにjava.utilパッケージ内のクラスです。

それとは別に、コードには多くのコンパイラ エラーがあります。

  • public string child- コンパイルしません。すべきではありStringませんstring
  • void compareTo(date d1, date d2)- ここで何をしようとしているのかわかりません。しかし、これもコンパイルされません。未定義の型 -date
  • を宣言し、Datum birthdayを使用して初期化しましnew Date(...)た。それもうまくいきません。
  • 何らかの理由で、クラスにメソッドがなく、コンストラクターがたくさんあるように感じます。私の提案は、そのコードを捨てて、新たに始めることです。
  • また、誕生日を格納するために多数の整数フィールドを使用しないでください。Calendar代わりにインスタンスを使用してください。
于 2013-10-06T18:10:02.347 に答える