0

当我在java中运行以下代码时:

import java.util.*;
class Solution{
    public static void main(String []argh)
    {
        Scanner sc = new Scanner(System.in);
        try{
            long x=sc.nextLong();
            System.out.println(x);
        }
        catch(Exception e){
            System.out.println(sc.next()+" can't be fitted anywhere.");
        }
       sc.close();
   }

}

并将输入输入为“23333333333333333333333333333333333333333”,它给出以下输出:

23333333333333333333333333333333333333333 can't be fitted anywhere.

sc.nextLong()抛出时,catch 块中的InputMismatchException如何获得与try 块中sc.next()输入的完全相同的值?sc.nextLong()它不应该在这里要求控制台输入代码的输入吗?

4

2 回答 2

3

long 的最大值是9223372036854775807,你的数字比那个大。尝试使用BigInteger. next()将数字作为String,因此它可以接受任何内容。请注意,next()获取该值是因为该值仍然存在于流中。

于 2015-09-18T08:25:39.707 回答
2

我相信你的问题不是关于数据类型和它的最大值,而是关于Scanner. 如果是这样,扫描仪 API会提到这一点:

当扫描器抛出 InputMismatchException 时,扫描器不会传递导致异常的令牌,以便可以通过其他方法检索或跳过它。

扫描仪仍然可以处理来自流的可用输入,以防万一InputMismatchException

于 2015-09-18T08:31:17.347 回答