打印超出远程的数字

时间:2015-09-25 09:29:08

标签: java

当我运行此代码并使用大于long范围的值时,输出为“0无法在任何地方安装”。 我想输出: “x(我已经给出了超出范围的输入)不能安装在任何地方”

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

        }
    }
}

4 个答案:

答案 0 :(得分:2)

如果该数字超出long范围,则无法使用long

使用没有此类限制的课程BigInteger

来自javadoc:

  

不可变任意精度整数

答案 1 :(得分:2)

BigInteger bg = new BigInteger(&#34; yourNumber&#34;);

参考:http://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html

祝你好运

答案 2 :(得分:1)

正如您已经遇到的那样,您无法使用documentCache=0.9。当值无法表示为long时,Scanner.nextLong()会抛出InputMismatchException

您可以使用String并尝试解析它:

long

请注意,我更改了捕获的异常:您应该避免捕获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

答案 3 :(得分:1)

您可以替换

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

通过

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

next()将获得String因{1}而未被nextLong()检索的令牌。