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

Java控制台实现单行内接收用户输入的方法(类似Python输入格式)

Java控制台实现单行内接收用户输入的方法(类似Python输入格式)

当然可以实现啦!你想要的这种和Python类似的单行输入效果,在Java里其实很容易做到,核心就是调整输出提示的方式,下面给你两种实用的实现方法:

方法一:使用Scanner类(新手友好,最常用)

Scanner是Java中处理控制台输入的常用工具,搭配System.out.print()(不带自动换行)就能轻松实现单行输入:

import java.util.Scanner;

public class InlineCalculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        // 用print代替println,避免输出提示后自动换行
        System.out.print("Enter Number One: ");
        int num1 = scanner.nextInt();
        
        System.out.print("Enter Number Two: ");
        int num2 = scanner.nextInt();
        
        // 简单的加法计算演示
        int result = num1 + num2;
        System.out.println("\nSum of the two numbers: " + result);
        
        scanner.close();
    }
}

运行后效果完全符合你的需求:

Enter Number One: 15
Enter Number Two: 25
Sum of the two numbers: 40

方法二:使用BufferedReader(适合复杂场景或追求性能)

如果需要处理更复杂的输入场景,或者对性能有要求,可以用BufferedReader来实现,同样搭配System.out.print()即可:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class InlineCalculator {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        
        System.out.print("Enter Number One: ");
        int num1 = Integer.parseInt(reader.readLine());
        
        System.out.print("Enter Number Two: ");
        int num2 = Integer.parseInt(reader.readLine());
        
        System.out.println("\nSum of the two numbers: " + (num1 + num2));
        
        reader.close();
    }
}

关键注意点

  • 一定要用System.out.print()而不是System.out.println():前者输出后不会自动添加换行符,输入光标会停在提示文本的末尾,实现同一行输入的效果;后者会强制换行,就是你之前遇到的那种情况。
  • 如果需要读取字符串输入,直接调用scanner.nextLine()或reader.readLine()即可,不需要做类型转换。

备注:内容来源于stack exchange,提问作者Keegan Welch

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 11:18:07