因爲這個問題似乎吸引非常廣泛/ 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類了!
在構造函數中這樣做很不常見,但這是您的決定。但是,仍然是,你的問題是什麼? – ParkerHalo
很酷,現在你的問題是什麼?如果您希望'sysout'提示用戶,那麼情況並非如此。 – hagrawal
將參數的異常或子字符串拋出到所需的長度 – null