You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何catch块的sc.next()能输出try块sc.nextLong()的输入值?

问题与解答

问题

以下是我的Java代码:

import java.util.*;

public class User {
  public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    int t=sc.nextInt();

    for(int i=0;i<t;i++)
    {

        try
        {
            long x=sc.nextLong();
            System.out.println(x+" can be fitted in:");
            if(x>=-128 && x<=127)System.out.println("* byte");
            if(x>=(Math.pow(-2,15)) && x<=(Math.pow(2,15))-1)System.out.println("* short");
            if(x>=(Math.pow(-2,31)) && x<=(Math.pow(2,31))-1)System.out.println("* int");
            if(x>=(Math.pow(-2,63)) && x<=(Math.pow(2,63))-1)System.out.println("* long");
        }
        catch(Exception e)
        {
            System.out.println(sc.next()+" can't be fitted anywhere.");
        }

    }
    sc.close();
  }
}

我搞不懂的是:当输入无法转换为long类型进入catch块后,catch块里的sc.next()为什么能打印出我在try块中输入的那个值?

解答

这是因为Scanner的输入缓冲区机制:

  • 当输入无法转成long的内容时,sc.nextLong()会尝试读取该输入,但因格式不匹配抛出异常,不过这个无效的输入字符串并没有被从Scanner的输入缓冲区中移除。
  • 进入catch块后调用sc.next(),会直接从缓冲区读取这个残留的无效输入字符串,所以能打印出你之前输入的内容。
  • 这么做还有个关键作用:如果不通过sc.next()清掉缓冲区里的无效输入,下一次循环的sc.nextLong()会再次读取到这个无效内容,导致无限抛出异常的死循环。

内容的提问来源于stack exchange,提问作者IASSCybercmd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 08:40:34