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

Java控制台输入:如何让两次输入值在同一行显示?

问题:Java中如何让输入的数量和价格显示在同一行?

当前使用的代码:

// Declare variables
String address;
String postal;
String country;

int qty;
double price;

// Input quantity and price for the iPhones
System.out.print("Enter the quantities and price of " + phone1 + ": " + "	");
qty = sc.nextInt();
price = sc.nextDouble();

执行后当前的显示效果:

Enter the quantities and price of iPhone 10:    1000
1399.99

期望实现的显示效果:

Enter the quantities and price of iPhone 10:    1000    1399.99

解决方案

你的代码本身已经支持读取同一行的多个输入,因为nextInt()和nextDouble()会自动跳过空格、换行等分隔符。当前出现换行是因为你输入第一个值后按了回车键。

要达到期望效果,只需要在输入时把两个值放在同一行,用空格分隔后再按回车即可,比如直接输入1000 1399.99再回车,控制台就会显示成你想要的样子。

如果要强制限制用户必须在同一行输入,需要用到控制台光标控制的特定平台API,这会增加代码复杂度,一般没必要采用这种方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 23:35:24