2014-10-02 189 views
-1

嘿那裏Stackoverflowers,Java - 靜態構造函數

我剛剛開始在Java中編程,並遇到一個奇怪的問題,有關打印對象。當創建一個類型gast的新對象時,用戶必須輸入他或她的生日。然而,如果我嘗試將其打印出來,我會返回0-0-0。這是爲什麼?順便說一下,如果我直接用參數構造函數創建一個新的數據,它可以正常工作。問題在哪裏?我無法弄清楚。我希望你們能幫助我。

在此先感謝!

public class Datum { 
    private static String patroon = "\\d{2}-\\d{2}-\\d{4}"; 
    public int dag; 
    public int maand; 
    public int jaar; 

    Datum(int dag, int maand, int jaar) { 
     System.out.print("constructor: " + dag); 
     this.dag = dag; 
     System.out.println(", dag: " + this.dag); 
     this.maand = maand; 
     this.jaar = jaar; 
    } 
    Datum() { 
     newDatum(); 
    } 

    /* */ 
    public static Datum newDatum() { 
     String input = Opgave5.userInput("Geboortedatum gast"); 
     boolean b = input.matches(patroon); 

     if (b) { 
      String[] str = input.split("-"); 

      int dag = Integer.parseInt(str[0]); 
      int maand = Integer.parseInt(str[1]); 
      int jaar = Integer.parseInt(str[2]); 

      Datum datum = new Datum(dag, maand, jaar); 
      System.out.println(datum); 
      return datum; 
     } 
     else { 
      return new Datum(); 
     } 
    } 

    public String toString() { 
     return this.dag + "-" + this.maand + "-" + this.jaar; 
    } 
} 

二等:

Gast() { 
    this.firstName = Opgave5.userInput("Voornaam gast"); 
    this.lastName = Opgave5.userInput("Achternaam gast"); 
    this.geboortedatum = new Datum(); 

    System.out.println("gast: " + this.geboortedatum); // <--- this prints out 0-0-0 

} 

public String toString() { 
    return this.firstName + " " + this.lastName + " " + this.geboortedatum; 
} 

回答

1

我覺得你不懂Java中的構造函數。你只是在構造函數中忽略了newDatum()的結果。此外,如果它確實具有預期的效果,它可能會在newDatum()內的構造函數調用中無限遞歸。使用這樣的東西;允許newDatum()編輯實例將工作:

Datum() { 
    newDatum(this); 
} 

public static void newDatum(Datum instance) { 
    String input = Opgave5.userInput("Geboortedatum gast"); 
    boolean b = input.matches(patroon); 

    if (b) { 
     String[] str = input.split("-"); 

     int dag = Integer.parseInt(str[0]); 
     int maand = Integer.parseInt(str[1]); 
     int jaar = Integer.parseInt(str[2]); 

     instance.dag = dag; 
     instance.maand = maand; 
     instance.jaar = jaar; 
     System.out.println(instance); 
    } 
    else { 
     new Datum(); 
    } 
    // ^^ Above code may be buggy, see my answer above code 
} 
+0

謝謝!現在我明白了我的錯誤:) – user3140559 2014-10-02 18:53:15

0

這條線:

this.geboortedatum = new Datum(); 

使用默認的構造函數。這將不會設置任何值。嘗試通過構造函數傳遞參數是這樣的:

this.geboortedatum = new Datum(1, 2, 3); 

如果你想利用你寫的static方法的優勢(這是你要求用戶輸入),然後執行以下操作:

this.geboortedatum = Datum.newDatum(); 
+0

我知道它的工作原理,如果我使用的構造函數的方式。重點是我需要通過userInput處理數據。 – user3140559 2014-10-02 18:45:35

+0

@ user3140559更新 – 2014-10-02 18:47:17

+0

不幸的是,將newDatum()更改爲Datum.newDatum()不起作用。他們都提到相同的方法,所以這是有道理的:) – user3140559 2014-10-02 18:50:12