java用in输入数组,如何从Java中的标准输入读取整数数组?

本文介绍了如何使用Java的BufferedReader从标准输入高效地读取一系列整数,并将它们存储到数组中。通过先读取id和N,然后遍历剩余的输入项,将每个整数解析并添加到数组中,实现了这一目标。同时,代码中包含了错误处理的提示,确保了数据读取的准确性。
摘要由CSDN通过智能技术生成

in one line from the standard input I have 3 types of integers: the first integer is id, the second integer is N - some number, and after that follows N integers, separeted by a single space which I want to store in array or ArrayList. How can I do this using BufferedReader? I have the following code:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

String[] line = br.readLine().split(" ");

int ID = Integer.parseInt(line[0]);

int N = Integer.parseInt(line[1]);

My question is is there any elegant way to read the rest of the line and to store it into array?

解决方案

How can I do this using BufferedReader?

You've already read/split the line, so you can just loop over the rest of the inputted integers and add them to an array:

int[] array = new int[N]; // rest of the input

assert line.length + 2 == N; // or some other equivalent check

for (int i = 0; i < N; i++)

array[i] = Integer.parseInt(line[i + 2]);

This will also let you handle errors within the loop (I'll leave that part to you, should you find it necessary).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值