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

Java中如何在用户输入位置添加">"提示符?

解决重复添加输入提示符的问题

你可以封装一个专用方法来统一处理提示信息与输入提示符的输出,避免每次手动拼接"\n > ":

public class InputHelper {
    // 统一输出提示文本和输入提示符
    public static void showPrompt(String promptMsg) {
        System.out.println(promptMsg);
        System.out.print("> ");
    }
}

使用时直接调用该方法即可:

// 替代原写法:System.out.println("what's your name\n > ")
InputHelper.showPrompt("what's your name");

如果不想单独创建工具类,也可以在当前类中定义私有方法实现相同逻辑:

public class YourMainClass {
    public static void main(String[] args) {
        showInputPrompt("what's your name");
        // 后续可重复调用
        showInputPrompt("how old are you");
    }

    private static void showInputPrompt(String msg) {
        System.out.println(msg);
        System.out.print("> ");
    }
}

这样每次只需传入提示内容,方法会自动完成换行和提示符的输出,彻底省去重复拼接字符串的操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 10:52:06