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

Java中Scanner为何将两个输入提示打印在同一行?

问题原因与解决方法

问题原因

你遇到的问题核心在于Scanner的nextInt()方法特性:它只会读取输入中的数字部分,不会处理输入数字后用户按下的换行符。这个残留的换行符会被紧接着的nextLine()直接读取,导致place变量被赋值为空字符串,程序随即执行下一行的提示语句,最终让"Enter a place: "和"Enter a college: "显示在同一行。

解决方法

有两种常用的修复方式:

方法1:在nextInt()后额外调用nextLine()消耗换行符

在读取完数字后,添加一行keyboard.nextLine()来吃掉残留的换行符,确保后续的nextLine()能正常读取用户输入:

import java.util.Scanner;

public class MadLibs {
    public static void main(String[] args) {
        String name, place, college, profession, animal, petName;
        int number;

        Scanner keyboard = new Scanner(System.in);

        System.out.print("Enter a name: ");
        name = keyboard.nextLine();

        System.out.print("Enter a number: ");
        number = keyboard.nextInt();
        // 新增:消耗掉数字输入后的换行符
        keyboard.nextLine();

        System.out.print("Enter a place: ");
        place = keyboard.nextLine();

        System.out.print("Enter a college: ");
        college = keyboard.nextLine();

        System.out.print("Enter a profession: ");
        profession = keyboard.nextLine();

        System.out.print("Enter an animal: ");
        animal = keyboard.nextLine();

        System.out.print("Enter a pet name: ");
        petName = keyboard.nextLine();

        keyboard.close();
    }
}

方法2:统一使用nextLine()读取所有输入,再转换数字类型

这种方式可以避免混合使用nextInt()和nextLine()带来的问题,先读取所有输入为字符串,再将数字字符串转为整数:

import java.util.Scanner;

public class MadLibs {
    public static void main(String[] args) {
        String name, place, college, profession, animal, petName;
        int number;

        Scanner keyboard = new Scanner(System.in);

        System.out.print("Enter a name: ");
        name = keyboard.nextLine();

        System.out.print("Enter a number: ");
        // 先读取字符串,再转为整数
        number = Integer.parseInt(keyboard.nextLine());

        System.out.print("Enter a place: ");
        place = keyboard.nextLine();

        System.out.print("Enter a college: ");
        college = keyboard.nextLine();

        System.out.print("Enter a profession: ");
        profession = keyboard.nextLine();

        System.out.print("Enter an animal: ");
        animal = keyboard.nextLine();

        System.out.print("Enter a pet name: ");
        petName = keyboard.nextLine();

        keyboard.close();
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 03:45:42