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

Java中Scanner的nextInt()与nextLine()配合时出现输入跳过问题求助

解决Scanner输入被跳过的问题

Hey there, I’ve run into this exact issue before—let’s break down what’s happening and fix it!

问题原因

The root of your input-skipping problem is how Scanner handles different input methods:

  • When you use scan.nextInt() to read an integer, it only grabs the numeric characters you type. It leaves the newline character (from you pressing Enter) sitting in the input buffer.
  • The first scan.nextLine() right after it will immediately read that leftover newline as an empty string, making it look like your input was skipped entirely.

Also, quick typo note: you wrote scan.nextImt() instead of scan.nextInt()—that’ll cause a compile error, so be sure to fix that first!

解决方法

You have two solid options to fix this:

方法1:吃掉残留的换行符

Right after calling nextInt(), add an extra scan.nextLine() to consume the leftover newline before reading your actual string inputs:

int amlinks = scan.nextInt();
scan.nextLine(); // 吃掉nextInt()留下的换行符
for (int i = 0; i < amlinks; i++) {
    System.out.print("[htmlbuilder.process]: text1 = ");
    String link1 = scan.nextLine(); // 现在能正常读取输入了
    System.out.print("[htmlbuilder.process]: text2 = ");
    String text1 = scan.nextLine();
    String link = "<p><a href='" + link1 + ".html'>" + text1 + "</a>";
    writer.write(link);
}

方法2:用nextLine()读取后转成整数(更健壮)

This approach avoids the newline issue entirely by reading the entire line for the integer, then parsing it to an int. It also handles cases where the user might accidentally type extra spaces or non-numeric characters (you can add a try-catch if you want to add error handling):

System.out.print("Enter number of links: ");
int amlinks = Integer.parseInt(scan.nextLine());
for (int i = 0; i < amlinks; i++) {
    System.out.print("[htmlbuilder.process]: text1 = ");
    String link1 = scan.nextLine();
    System.out.print("[htmlbuilder.process]: text2 = ");
    String text1 = scan.nextLine();
    String link = "<p><a href='" + link1 + ".html'>" + text1 + "</a>";
    writer.write(link);
}

额外小修正

I noticed a typo in your Writer initialization code—here’s the cleaned-up version:

Writer writer = null;
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileID + ".html"), "utf-8"));

That should get your input working as expected! Let me know if you run into any other snags.

内容的提问来源于stack exchange,提问作者user-1561363397

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:54:55