2016-11-14 64 views
-1

我有一個名爲客戶端的類,我將用來存儲客戶端註冊表信息,他們的名字和電子郵件,這將是他們的帳戶登錄信息的Java文件。我在這裏有點卡住了。實現一個帳戶類

這是一個有點什麼,我至今

public class ClientAccount { 

    private String name; 
    private String email; 
/**This intializes an instance of ClientAccount 
    public ClientAccount(String name, String email) { 

    this.name = name; 
    this.email = email; 
} 

該代碼將返回一個字符串與客戶的姓名和電子郵件的類。

現在我需要一個從字符串創建客戶端和實例的方法。

/** 
* Creates an instance of Client from a String. 
* 
* @param s a String 
* @return an instance of Client 
* @requires s is a string that contains the email address of the client 
* and its name, separated by a comma (,). The string must contain exactly 
* one comma. 
* @ensures the returned value c is such that c.getEmail is equal to the 
* email address specified in s and c.name is equal to the name specified 
* in s. 
*/ 
public static ClientAccount fromString(String s) { 

} 

s是包含客戶端 和它的名字的電子郵件地址,用逗號分隔的字符串。返回客戶端實例

public String toString() { 
    // TODO 
    return this.email+","+this.name; 
} 
+2

問題是? – UnholySheep

+0

「我有一個名爲Client的類的java文件」我看到一個名爲'ClientAccount'的類,而不是'Client'。我建議你學會對細節進行這樣的挑剔,因爲當你試圖編程時,電腦是無情的文字。 –

+0

@ Code-Apprentice的確如此,因爲在我發佈問題之前,我改變了一些代碼。 – Exzlanttt

回答

0

您需要解析輸入字符串以獲取單獨的名稱和電子郵件。如果輸入的格式與您從toString()返回的格式相同,則可以使用String.split()。我建議你使用Google來查找String類的文檔並閱讀這個方法。有一點需要注意,電子郵件或名稱中沒有逗號。這不應該是一個電子郵件的問題,但可能是一個名稱取決於它是如何進入的。

+0

我只是不確定如果我的toString方法甚至是rigth。 – Exzlanttt

+0

@Exzlanttt你的問題沒有提供足夠的信息來判斷它是否正確。 –

+0

我可以發佈fromString方法的javadoc – Exzlanttt

0

您可以使用java.lang.Stringsplit方法,並獲得元素(電子郵件,姓名等),如下圖所示:

public static ClientAccount fromString(String s) { 
    //split the string using , 
    String[] elements = s.split(","); 

    //elements[1] is name 
    //elements[0] is email 
    ClientAccount clientAccount = new ClientAccount(elements[1], elements[0]); 

    return clientAccount; 
} 

ClientAccount類具有getter和setter方法:

public class ClientAccount { 

      private String name; 
      private String email; 

      public ClientAccount(String name, String email) { 
      this.name = name; 
      this.email = email; 
     } 

     public String getName() { 
      return name; 
     } 

     public void setName(String name) { 
      this.name = name; 
     } 

     public String getEmail() { 
      return email; 
     } 

     public void setEmail(String email) { 
      this.email = email; 
     } 
    } 
+0

如果我想要一個公共字符串getEmail(){,返回值是什麼?像 - > return clientAccount.email? – Exzlanttt

+0

是的,你需要getters和setters,請參閱上面的類 – developer

+0

@Exzlanttt我建議你瞭解訪問元素與參考變量和當前對象的元素之間的區別。 –

0

另外,您也可以使類中的構造函數過載爲:

public ClientAccount(String s) { 
    String[] elements = s.split(","); 

    this.name = elements[1]; 
    this.email = elements[2]; 
} 

...然後在別處:ClientAccount clientAccount = new ClientAccount(s);

請注意,這個簡單的版本假設您有一個漂亮的輸入字符串。在真正的應用程序中,您可能希望在分割之前執行一些正則表達式匹配,以檢查字符串是否具有正確的格式(電子郵件+逗號+名稱)。