2015-09-25 99 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