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

Java代码输出出现额外1的问题:为何输出多出一个字段?

为啥你的Java代码输出多了个"1"?

嘿,这问题我熟!根源出在Scanner的nextInt()和nextLine()的行为差异上:

  • nextInt()只读取输入里的数字,完全不管数字后面的换行符,这个换行符会留在输入缓冲区里没被处理。
  • 当你第一次调用nextLine()的时候,它直接就把这个残留的空换行(也就是一个空字符串)读进来了。
  • 你对这个空字符串执行split("\\s"),得到的数组里会有一个空字符串元素,所以values.length就是1——这就是你看到的第一个输出"1"的由来!
怎么修复?

给你两种靠谱的解决办法:

办法一:吃掉nextInt()后的换行符

在nextInt()之后,额外调用一次nextLine(),专门用来读取并丢弃那个残留的换行符:

public class TestClass { 
    public static void main(String args[] ) throws Exception { 
        Scanner s = new Scanner(System.in); 
        int t = s.nextInt(); 
        s.nextLine(); // 加这一行,把换行符消费掉
        for(int i=0;i<t;i++) { 
            String name = s.nextLine(); 
            System.out.println(name); 
            String[] values = name.split("\\s"); 
            System.out.println(values.length); 
        } 
        s.close(); 
    } 
}

办法二:统一用nextLine()读所有输入

要是不想折腾换行符的问题,干脆全程用nextLine()读取输入,再把第一行的字符串转成整数就行:

public class TestClass { 
    public static void main(String args[] ) throws Exception { 
        Scanner s = new Scanner(System.in); 
        int t = Integer.parseInt(s.nextLine()); // 直接读第一行转整数
        for(int i=0;i<t;i++) { 
            String name = s.nextLine(); 
            System.out.println(name); 
            String[] values = name.split("\\s"); 
            System.out.println(values.length); 
        } 
        s.close(); 
    } 
}

这两种方法都能让输出和你预期的一致,再也不会多那个讨厌的"1"啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:58:51