[英]JAVA - how to set input range validation for user input
public static void main(String[] args) {
// TODO Auto-generated method stub
//Scanner for AccountNumbers
Scanner AccountIn = new Scanner(System.in);
ArrayList<String> AccountNumber = new ArrayList<String>();
System.out.println("Create Account Number");
while(AccountIn.hasNextLine()>0 &&AccountIn.hasNextLine() < 9){
//EveryTime AccountNumber Is created store in Array
AccountNumber.add(AccountIn.nextLine());
money = reader.readDouble("Enter Starting Amount Of Money");
}
}
我正在嘗試使掃描儀“ AccountIn”的用戶輸入大於0且小於9怎么辦? 我應該創建輸入變量然后在while循環中列出嗎? 還是應該使用try and catch異常?
我將使用略有不同的方法。 使用do-while
循環先驗證輸入。 如果輸入通過了驗證循環的檢查,請繼續添加到列表:
String input = "";
Scanner scn = new Scanner(System.in);
do{
System.out.print("Please enter account number:");
input = scn.nextLine();
}while(input.length() != 9);
accountNumbers.add(input); //Note: I write "accountNumbers" instead of "AccountNumber"
注意 :由於您要驗證您的帳號,因此它不僅應檢查其0到9個字符。 相反,它應該檢查一下是否恰好有9個字符。
我應該創建輸入變量然后在while循環中列出嗎? 還是應該使用try and catch異常?
我會說異常處理用於處理您不希望發生的異常情況。 因此,您不應使用try-catch
塊來進行驗證。 使用do-while
或while
循環是合適的。
方法hasNextLine()
僅返回類似於javadoc( https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNextLine%28%29 )的布爾值
要獲取實際值,必須使用nextLine()
或nextInt()
嘗試類似:
while(AccountIn.hasNextLine()){
int accountValue = AccountIn.nextInt();
if (accountValue > 0 && accountValue < 9) {
// Something usefull.
}
}
如果要在用戶輸入中檢查字符的校驗數,請嘗試這種方式。
Scanner AccountIn = new Scanner(System.in);
ArrayList<String> AccountNumber = new ArrayList<String>();
System.out.println("Create Account Number");
String acountNumber = AccountIn.nextLine();
while(acountNumber.length() < 9 && acountNumber.length() > 0){
System.out.println("Account Number Should Contain 9 Numbers. Please re enter:");
acountNumber = AccountIn.nextLine();
}
AccountNumber.add(acountNumber);
System.out.println("Account Number Saved");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.