2014-04-24 33 views
0

我只想檢查用戶輸入的10位數字。用戶輸入可以是1到10位數字。 我還增加import java.util.* ;爲什麼我在if條件中出現異常?

問題:歌廳異常,當用戶輸入的值大於10。 使用龍如果用戶輸入是超出範圍,則相同的錯誤之後。 錯誤:在厚望線程 「主要」 java.util.InputMismatchException

我想限制用戶只能輸入1到10個數字僅

更新代碼

for(int i=0;i<b.length;i++) 
    { 
     if(b[i][0]==0) 
     { 
      try 
      { 
       System.out.println("Enter the account number:"); 
       a=sc.nextLong(); 
       int lth = (int) Math.log10(a) + 1; 
       if((lth <= 10) && (lth > 0)){ 
        System.out.println("Account number is valid"); 
        break; 
       } 
      } 
      catch(InputMismatchException e) 
      { 
       System.out.println("not a valid input"); 
      } 

     } 
    } 
+1

是否有10位數字,適合在'int'? –

+0

爲什麼你得到一個int然後將其轉換爲一個字符串,爲什麼不只是得到一個字符串開始?如果你用數值做數學,它是一個數字(int,double,long等),否則它是一個String。 – Michael

+0

int的最大值是'2,147,483,647' – Braj

回答

1

變化

a=sc.nextInt(); 

a=sc.nextLong(); 

,或者如果你想字符串只有這樣,你可以按照

String input=sc.next(); 
s1=a.toString();//no need for this 

試試下面做

try 
      { 
       System.out.println("Enter the account number:"); 
       String ip=sc.next(); 
       int lth = ip.length(); 
       if((lth <= 10) && (lth > 0)){ 
        System.out.println("Account number is valid"); 
        break; 
       } 
      } 
+0

請檢查更新後的代碼 –

+0

什麼是數據類型? –

+0

LONG INTEGER .... long a = 0; –

相關問題