2015-12-04 190 views
0

我想在我的「成員」構造函數(代碼要遵循 - 它非常簡單)中創建一個while循環,以確保成員id是10個字符,或者pin號是4個字符while循環在java驗證

eg雖然ID/pinNumber ID不10/4長 停止構造正在取得 打印「請輸入ID/pinNumber是10/4個字符長」

這是我的代碼

/** 
* Constructor for objects of class Member 
*/ 
public Member(String giveName, String giveID, String givePinNumber, int giveMoney) 
{ 
    memberName = giveName; 
    id = giveID; 
    if(id.length() > 10) 
     System.out.println("Please input an id less than 10 characters"); 

    pinNumber = givePinNumber; 
    if(pinNumber.length() > 10) 
     System.out.println("Please input a pinNumber less than 10 characters"); 

    store = null; 
    item = null; 
    money = giveMoney; 
} 
+6

在構造函數中這樣做很不常見,但這是您的決定。但是,仍然是,你的問題是什麼? – ParkerHalo

+1

很酷,現在你的問題是什麼?如果您希望'sysout'提示用戶,那麼情況並非如此。 – hagrawal

+0

將參數的異常或子字符串拋出到所需的長度 – null

回答

2

因爲這個問題似乎吸引非常廣泛/ PARLY錯誤的答案,我將在這裏澄清一些事情:

可能循環在構造函數從控制檯獲取輸入,但我會強烈建議不要使用的代碼類型:

Member(String giveName, String giveID, String givePinNumber, int giveMoney) { 
    Scanner sc = new Scanner(System.in); 

    id = giveID; 
    while (id.length() != 10) { 
     System.out.println("Enter id with length of 10: "); 
     id = sc.nextLine(); 
    } 

    pinNumber = givePinNumber; 
    while (pinNumber.length() != 4) { 
     System.out.println("Enter pin-number with length of 4: "); 
     pinNumber = sc.nextLine(); 
    } 

    store = null; 
    item = null; 
    money = giveMoney; 

    sc.close(); 
} 

通常這會從誰是創建成員對象之一來完成!如果會員對象被創建我的主方法,你可以/會做這樣的事情:

public static void main(String[] args) { 
    Scanner sc = new Scanner(System.in); 

    String id; 
    System.out.println("Please enter id: (length must be 10)"); 
    while ((id = sc.nextLine()).length() != 10) 
     System.out.println("Length of id must be 10, try again: "); 

    String pin; 
    System.out.println("Please enter id: (length must be 10)"); 
    while ((pin = sc.nextLine()).length() != 4) 
     System.out.println("Length of pin must be 4, try again: "); 

    sc.close(); 

    Member foo = new Member("Peter", id, pin, 1000000); 
} 

和您的會員構造函數看起來是這樣的:

Member(String giveName, String giveID, String givePinNumber, int giveMoney) { 
    if (giveID.length() != 10) 
     throw new IndexOutOfBoundsException("ID-length must be 10!"); 
    if (givePinNumber.length() != 4) 
     throw new IndexOutOfBoundsException("PIN-length must be 4!"); 

    id = giveID; 
    pinNumber = givePinNumber; 
    store = null; 
    item = null; 
    money = giveMoney; 

} 

這種方法會讓你的代碼清晰可讀但更重要:可重複使用!考慮一個你沒有控制檯的java-app ...你將無法再使用你的Member類了!

+0

這真是太棒了 - 我的講師告訴我要在我的構造函數中進行驗證,並且我不知道該怎麼做,但是這已經明確地爲我解決了,謝謝! –

1

我想這種驗證屬於視圖層: *詢問值 *進行驗證 *顯示錯誤並詢問正確的值 當您調用構造函數時,傳遞給它的數據必須正確。

因此,您不需要在構造函數中進行驗證。

實際上,構造函數的目標是初始化類的字段。沒有驗證,也沒有拋出異常。