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

Eclipse中Java循环先执行打印语句再运行其余代码的问题

解决Eclipse中Java for循环输入异常的问题

我完全懂你遇到的糟心事——用sc.nextInt()读取测试用例数后,第一次进入for循环时,输入步骤直接被跳过,打印语句先跑了起来,这根本就是输入缓冲区里残留的换行符在捣乱!

问题根源

  • sc.nextInt()只会读取你输入的整数部分,但你输入完数字后按下的回车键(也就是换行符\n)会留在输入缓冲区里。
  • 当第一次执行sc.nextLine()时,它会直接读取这个残留的换行符,相当于得到了一个空字符串,所以程序立刻跳到下一行打印"Enter String 2",看起来就像是循环先执行了打印语句,跳过了输入环节。

两种修复方案

方案一:吃掉nextInt()残留的换行符

在nextInt()之后额外加一行sc.nextLine(),专门清空缓冲区里的换行符:

import java.util.Scanner; 
public class Sample { 
    public static void main(String[] args) { 
        int testcase ; 
        String s1; 
        String s2; 
        Scanner sc = new Scanner(System.in); 
        System.out.println("Enter test cases"); 
        testcase = sc.nextInt(); 
        // 新增这行,吃掉nextInt()留下的换行符
        sc.nextLine();
        for(int i=1 ; i<=testcase; i++) { 
            System.out.println("Enter String 1"); 
            s1= sc.nextLine(); 
            System.out.println("Enter String 2"); 
            s2= sc.nextLine(); 
            // 补全你的WeightChecker调用代码
            System.out.println(WeightChecker.checkStringWeight(s1, s2));
        }
        // 记得关闭Scanner释放资源
        sc.close();
    }
}

方案二:全程用nextLine()读取输入(更稳妥)

放弃nextInt(),直接用sc.nextLine()读取测试用例数的整行输入,再转成整数,从根源避免缓冲区问题:

import java.util.Scanner; 
public class Sample { 
    public static void main(String[] args) { 
        int testcase ; 
        String s1; 
        String s2; 
        Scanner sc = new Scanner(System.in); 
        System.out.println("Enter test cases"); 
        // 读取整行后转成int
        testcase = Integer.parseInt(sc.nextLine()); 
        for(int i=1 ; i<=testcase; i++) { 
            System.out.println("Enter String 1"); 
            s1= sc.nextLine(); 
            System.out.println("Enter String 2"); 
            s2= sc.nextLine(); 
            System.out.println(WeightChecker.checkStringWeight(s1, s2));
        }
        sc.close();
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:57:54