当 Scanner.nextLong() 从 try 块中抛出 InputMismatchException 那么 Scanner.next() 如何在 catch 块中获得相同的值?

When Scanner.nextLong() throws InputMismatchException from try block then how does the Scanner.next() get the same value in catch block?

当我运行下面的代码在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() 抛出 InputMismatchException 那么 catch 块中的 sc.next() 如何获得与 try 块中为 sc.nextLong() 输入的完全相同的值?它不应该在这里要求控制台输入代码输入吗?

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

我认为您的问题不是关于数据类型及其最大值,而是关于 Scanner。如果是这样,Scanner API 会提到:

When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.

InputMismatchException

的情况下,扫描器仍然可以处理来自流的可用输入