2016-02-12 185 views
1
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和catch異常?JAVA - 如何設置用戶輸入的輸入範圍驗證

+0

你想檢查'AccountIn'中的章程嗎? –

+0

是的。 AccountIn是用戶輸入賬號的掃描儀。 – Ahmed

+0

@Ahmed看看我的解決方案。 – user3437460

回答

1

我會用稍微不同的方法。首先使用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和catch異常?

我會說異常處理用於處理您不希望發生的異常情況。因此,您不應該使用try-catch塊來處理您的驗證。使用do-whilewhile循環是合適和充分的。

0

的方法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. 

    } 
} 
+0

嗨,謝謝你的回答,但我可能沒有詳細說明,對不起,我很抱歉,但我的意思是,如果我可能有一個用戶輸入字符爲9 123456789而不只是一個值:)希望你明白。 – Ahmed

0

如果您希望用戶輸入中的charaters的檢查號碼以這種方式嘗試。

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");