2014-12-02 51 views
3
do{ 
     out.println("\n---------------------------------"); 
     out.println("---------------------------------"); 
     out.print("Please type your acces card number: "); 

    try{ 
     card = input.nextInt(); 

     if(card.length != 10){ 
      out.println("The number you typed is incorrect"); 
      out.println("The number must be 10 numbers long"); 
     continue; 
      } 
     } 

     catch(InputMismatchException ex){ 
      } 
    }while(true);  

林試圖使卡是10個字符長。像(1234567890),並且如果用戶輸入(123),還是應該出現(123456789098723)的錯誤消息。 card.length似乎沒有工作。我如何可以設置多少個字符可以輸入的限制? (JAVA)

+0

也許你可以嘗試接收純字符串,然後解析爲整數。 – HuStmpHrrr 2014-12-02 02:23:28

+1

我贊同「將卡號視爲字符串」的方法 - 通常卡號不需要對它們進行數學運算,並且adn可以包含前導零,因此使用字符串實際上是一種明智的表示形式。 – 2014-12-02 02:27:07

回答

3

只是改變INT爲String

String card = input.next(); 
    if(card.length() != 10){ 
     //Do something 
    } 

您可以輕鬆地將其轉換爲int後

int value = Integer.parseInt(card); 
0

在Java中,你不能讓一個intlength。找到的位數最簡單的方法是將其轉換爲String。但是,您也可以通過一些數學來確定數字的長度。你可以找到更多的信息here

3

你可以改變

if(card.length != 10){ 

喜歡的東西

if(Integer.toString(card).length() != 10){ 

。當然,這是可能的用戶輸入

0000000001 

這將是一樣1。你可以嘗試

String card = input.next(); // <-- as a String 

然後

if (card.length() == 10) 

最後

Integer.parseInt(card) 
0

你不能得到int的長度。這將是更好的得到輸入爲String,並將其轉換成一個int以後,如有需要。你可以做的錯誤在你的while循環檢查,如果你喜歡短路,你可以有同時檢查也顯示您的錯誤信息:

out.println("\n---------------------------------"); 
out.println("---------------------------------"); 
out.print("Please type your access card number: "); 

do { 
    try { 
     card = input.nextLine(); 
    } catch (InputMismatchException ex) { 
     continue; 
    } 
} while (card.length() != 10 && errorMessage()); 

,有你的errorMessage函數返回true,並顯示錯誤消息:

private boolean errorMessage() 
{ 
    out.println("The number you typed is incorrect"); 
    out.println("The number must be 10 numbers long"); 
    return true; 
} 
相關問題