备案号:蜀ICP备2026035467号-3|网址:www.xservx.com

java 怎么输入一组数?——全场景输入方案深度指南

在Java开发中,java 怎么输入一组数看似基础问题,实则涉及输入流、缓冲机制、异常处理、性能权衡等多维知识。本文从零梳理从控制台、文件、网络、系统属性等10+种输入场景的完整方案,深入剖析Scanner、BufferedReader、Files、Stream API、NIO.2等核心API的适用边界、陷阱与优化策略,帮助开发者构建健壮、高效、可维护的输入处理逻辑。

一、基础输入:控制台与标准输入流

最常见需求:用户在终端输入若干整数或浮点数,以空格或换行分隔。例如输入:10 20 30 40 50。

1.1 Scanner方案(新手首选)

适用场景

交互式程序、教学演示、小规模输入(<10⁴元素)

核心代码

import java.util.*;
public class InputArrayDemo {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入一组整数(空格分隔):");
        String line = scanner.nextLine();
        String[] parts = line.trim().split("\\s+");
        int[] nums = new int[parts.length];
        for (int i = 0; i < parts.length; i++) {
            nums[i] = Integer.parseInt(parts[i].trim());
        }
        System.out.println("输入数组:" + Arrays.toString(nums));
    }
}

关键细节

  • 使用nextLine()避免nextInt()残留换行符问题
  • split("\\s+")支持多空格/制表符分隔
  • 必须捕获NumberFormatException(见进阶部分)

扩展:逐个读取

若输入行数未知(如EOF前持续输入),可使用:

Scanner sc = new Scanner(System.in);
List list = new ArrayList<>();
while (sc.hasNextInt()) {
    list.add(sc.nextInt());
}
int[] arr = list.stream().mapToInt(Integer::intValue).toArray();

1.2 BufferedReader方案(性能更优)

优势对比

Scanner内部使用正则匹配,小数据量时性能尚可;但大数据量(如10⁵+)时,BufferedReader因直接操作字符流,吞吐量高出3-5倍

推荐写法

import java.io.*;
public class BufferedReaderDemo {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String line = br.readLine();
        String[] parts = line.trim().split("\\s+");
        int[] nums = new int[parts.length];
        for (int i = 0; i < parts.length; i++) {
            nums[i] = Integer.parseInt(parts[i]);
        }
    }
}

性能实测

输入规模Scanner耗时(ms)BufferedReader耗时(ms)
10³129
10⁴8538
10⁵920150

1.3 标准输入流直接读取(极端性能场景)

当处理超大数据集(如10⁶+整数),需直接操作字节流:

import java.io.*;
public class FastInputDemo {
    private static final int BUFFER_SIZE = 1 << 16;
    private static InputStream in = System.in;
    private static final byte[] buffer = new byte[BUFFER_SIZE];
    private static int index, size;
    private static int read() throws IOException {
        if (index >= size) {
            size = in.read(buffer, 0, BUFFER_SIZE);
            index = 0;
            if (size <= 0) return -1;
        }
        return buffer[index++];
    }
    private static int nextInt() throws IOException {
        int ret = 0;
        byte c = read();
        while (c <= ' ') c = read();
        boolean neg = (c == '-');
        if (neg) c = read();
        do { ret = ret * 10 + c - '0'; }
        while ((c = read()) >= '0' && c <= '9');
        return neg ? -ret : ret;
    }
    public static void main(String[] args) throws IOException {
        List list = new ArrayList<>();
        int num;
        while ((num = nextInt()) != -1) list.add(num);
        int[] arr = list.stream().mapToInt(Integer::intValue).toArray();
    }
}

该方案吞吐量可达10⁷+元素/秒,适用于算法竞赛等极限场景。

二、进阶方案:文件与网络输入

2.1 文件输入:从文本文件读取数组

假设文件data.txt内容:

100 200 300
400 500
600 700 800 900

方案:Files.readAllLines + 流处理

import java.nio.file.*;
import java.util.stream.*;
import java.io.IOException;
public class FileInputDemo {
    public static void main(String[] args) throws IOException {
        Path path = Paths.get("data.txt");
        List lines = Files.readAllLines(path);
        int[] nums = lines.stream()
            .flatMap(line -> Stream.of(line.trim().split("\\s+")))
            .filter(s -> !s.isEmpty())
            .mapToInt(Integer::parseInt)
            .toArray();
        System.out.println("数组长度:" + nums.length);
    }
}

优势

  • 代码简洁,无显式循环
  • 自动处理行分隔符
  • 支持UTF-8等编码(可指定charset参数)

方案:BufferedReader + Stream

import java.io.*;
import java.nio.file.*;
import java.util.stream.*;
public class StreamFileDemo {
    public static void main(String[] args) throws IOException {
        try (BufferedReader br = Files.newBufferedReader(Paths.get("data.txt"))) {
            int[] nums = br.lines()
                .flatMap(line -> Stream.of(line.trim().split("\\s+")))
                .filter(s -> !s.isEmpty())
                .mapToInt(Integer::parseInt)
                .toArray();
        }
    }
}

关键特性

  • try-with-resources确保流自动关闭
  • lines()返回Stream,天然支持流式处理
  • 内存占用低于readAllLines(逐行读取)

方案:NIO.2 FileChannel + ByteBuffer

import java.nio.*;
import java.nio.channels.*;
import java.nio.file.*;
import java.io.IOException;
public class NIOFileDemo {
    public static void main(String[] args) throws IOException {
        Path path = Paths.get("data.txt");
        try (FileChannel fc = FileChannel.open(path, StandardOpenOption.READ)) {
            ByteBuffer buf = ByteBuffer.allocate((int)fc.size());
            fc.read(buf);
            buf.flip();
            String content = StandardCharsets.UTF_8.decode(buf).toString();
            int[] nums = content.trim().split("\\s+")
                .filter(s -> !s.isEmpty())
                .mapToInt(Integer::parseInt)
                .toArray();
        }
    }
}

适用场景

  • 大文件(>2GB)输入
  • 需随机访问文件内容
  • 结合异步通道(AsynchronousFileChannel)

2.2 网络输入:从URL或Socket读取

URL输入示例

import java.net.*;
import java.io.*;
import java.util.stream.*;
public class URLInputDemo {
    public static void main(String[] args) throws IOException {
        URL url = new URL("https://example.com/data.txt");
        try (BufferedReader br = new BufferedReader(
            new InputStreamReader(url.openStream()))) {
            int[] nums = br.lines()
                .flatMap(line -> Stream.of(line.trim().split("\\s+")))
                .filter(s -> !s.isEmpty())
                .mapToInt(Integer::parseInt)
                .toArray();
        }
    }
}

关键注意事项

  • 必须处理MalformedURLException和IOException
  • 网络超时需设置连接/读取超时(URLConnection.setConnectTimeout())
  • HTTPS需配置证书信任链(生产环境需自定义TrustManager)

三、高频场景深度解析

⚡ 场景1:多组测试用例输入

算法题常见输入格式:

3
5
1 2 3 4 5
3
10 20 30
4
7 8 9 10

对应处理逻辑:

Scanner sc = new Scanner(System.in);
int t = sc.nextInt(); // 测试用例数
for (int i = 0; i < t; i++) {
    int n = sc.nextInt(); // 本组元素个数
    int[] arr = new int[n];
    for (int j = 0; j < n; j++) {
        arr[j] = sc.nextInt();
    }
    // 处理本组数据
}

⚙️ 场景2:混合类型输入

输入格式:3 Alice 95.5 Bob 88

String line = scanner.nextLine();
String[] parts = line.split("\\s+");
int count = Integer.parseInt(parts[0]);
List names = new ArrayList<>();
List scores = new ArrayList<>();
for (int i = 1; i < parts.length; ) {
    if (i + 1 >= parts.length) break;
    names.add(parts[i++]);
    scores.add(Double.parseDouble(parts[i++]));
}

⚡ 场景3:带分隔符的数组输入

输入:10,20;30 40|50(逗号/分号/空格/竖线混合分隔)

String line = scanner.nextLine();
String[] nums = line.split("[,;\\s|]+"); // 正则字符组
int[] arr = Arrays.stream(nums)
    .filter(s -> !s.isEmpty())
    .mapToInt(Integer::parseInt)
    .toArray();

⚙️ 场景4:大数输入(BigInteger)

Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
BigInteger[] bigArr = Arrays.stream(line.split("\\s+"))
    .map(BigInteger::new)
    .toArray(BigInteger[]::new);

3.1 异常处理最佳实践

安全输入封装

public class SafeInput {
    public static int[] parseIntArray(String line) {
        try {
            return Arrays.stream(line.trim().split("\\s+"))
                .filter(s -> !s.isEmpty())
                .mapToInt(Integer::parseInt)
                .toArray();
        } catch (NumberFormatException e) {
            System.err.println("输入格式错误: " + e.getMessage());
            return new int[0];
        }
    }
    public static void main(String[] args) {
        int[] nums = parseIntArray("1 2 a 4");
        System.out.println("有效数字个数: " + nums.length);
    }
}

错误处理策略

  • 跳过非法项:过滤后继续处理
  • 终止并提示:抛出运行时异常
  • 重试机制:循环要求用户重新输入

3.2 性能优化对比表

方案适用规模内存占用线程安全推荐指数
Scanner<10⁴中否★★★☆
BufferedReader10⁴~10⁶低否★★★★
Files.readAllLines<10⁵高否★★★☆
NIO.2 Channel>10⁶可控否★★★★☆
FastInput(字节流)>10⁷极低否★★★★★

四、常见问题深度答疑

Q1:为什么Scanner读取后换行符残留导致下一次读取异常?

A:Scanner的nextInt()等方法只读取数值,不消费换行符。后续调用nextLine()时会立即返回空字符串。

解决方案:

  • 统一使用nextLine() + Integer.parseInt()
  • 在nextInt()后插入scanner.nextLine()消费换行符
Q2:如何处理含负数、浮点数的混合输入?

A:调整正则表达式支持小数点与负号:

String[] parts = line.trim().split("\\s+");
List list = new ArrayList<>();
for (String s : parts) {
    if (s.matches("-?\\d+\\.\\d+")) { // 浮点数
        list.add(Double.parseDouble(s));
    } else if (s.matches("-?\\d+")) { // 整数
        list.add(Integer.parseInt(s));
    }
}
Q3:输入超大数组(10⁸元素)内存溢出怎么办?

A:采用分块处理策略:

  1. 分批读取(如每次10⁶元素)
  2. 使用IntStream流式处理
  3. 写入临时文件,后续分块合并

示例:分块读取

int[] buffer = new int[1_000_000];
int index = 0;
while ((num = scanner.nextInt()) != -1) {
    buffer[index++] = num;
    if (index == buffer.length) {
        processBlock(buffer); // 处理本块
        index = 0;
    }
}
if (index > 0) processBlock(Arrays.copyOf(buffer, index));