2015-09-25 47 views
1

當我運行此代碼並使用大於long範圍的值時,則輸出爲「0無法在任何位置安裝」。 我想輸出: 「×(我所給定的輸入這是很長的範圍之外)不能在任何地方安裝」打印一個超出範圍的數字

import java.util.*; 
import java.io.*; 

class Solution { 
    public static void main(String[] argh) { 
     Scanner sc = new Scanner(System.in); 
     int t = sc.nextInt(); 

     for (int i = 0; i < t; i++) { 
      long x = 0; 
      try { 
       x = sc.nextLong(); 
       System.out.println(x + " can be fitted in:"); 
       if (x >= -128 && x <= 127) 
        System.out.println("* byte"); 
       if (x >= -32768 && x <= 32767) 
        System.out.println("* short"); 
       if (x >= -2147483648 && x <= 2147483647) 
        System.out.println("* int"); 
       if (x >= -9223372036854775808l && x <= 9223372036854775807l) 
        System.out.println("* long"); 

       // Complete the code 
      } catch (Exception e) { 
       System.out.println(x + " can't be fitted anywhere."); 
      } 

     } 
    } 
} 
+0

不要忘了在最後關閉'Scanner':sc.close();'。 –

回答

1

您可以通過

} catch (InputMismatchException e) { 
    System.out.println(sc.next() + " can't be fitted anywhere."); 
} 

next()更換

} catch (Exception e) { 
    System.out.println(x + " can't be fitted anywhere."); 
} 

將獲得作爲String不是由nextLong()由於異常檢索到的令牌。

+0

Florent Bayle在此先感謝我希望得到的答案與您給出的答案相同。但是,您可以具體說明它是由jvm ???內部完成的,當long的範圍不匹配時,它將自動轉換爲sc.next( )??怎麼樣?? –

+0

@RakeshYadav'sc.nextLong()'當下一個標記不能被解析爲'long'時'拋出'InputMismatchException'。當出現這種情況時,您將進入「catch」模塊。 'sc.next()'會讀取下一個標記(不是由'sc.nextLong()'讀取的標記)並將其作爲'String'返回(所以它不需要適合'long ',因爲它是一個'String')。 –

2

如果數量超出long你可以在範圍不要用long

使用還沒有這種限制類BigInteger

從Javadoc中:

不可變任意精度整數

1

正如你已經遇到過,你不能使用long這一點。當值不能表示爲long時,Scanner.nextLong()將拋出InputMismatchException

您可以使用一個字符串,並嘗試分析它:

long x = 0; 
String input = ""; 
try { 
    input = sc.nextLine(); 
    x = Long.parseLong(input); 
    System.out.println(x+" can be fitted in:"); 
    // rest of code 
} catch(NumberFormatException e) { 
    System.out.println(input + " can't be fitted anywhere."); 
} 

注意,我改變了逮住例外:你應該避免受涼Exception,喜歡最具體Exception