如何使用BufferedReader对象从java中的一行读取多个整数值?
我正在使用BufferedReader类来读取我的java程序中的输入。
我想读取用户输入的输入,用户可以用空格单行输入多个整数数据。
我想在整数数组中读取所有这些数据。
I am using BufferedReader class to read inputs in my java program. I want to read inputs from user who can enter multiple integer data in single line with space. I want to read all these data in an integer array.
输入格式 -
用户首先输入他/她想要输入的数字
Input format- user first enters how many numbers he/she want to enter
然后下一行中有多个整数值 -
and then multiple integer values in next single line-
INPUT:
5
2 456 43 21 12
2 456 43 21 12
现在,我使用对象读取输入(br)BufferedReader
now,i read input using object(br) of BufferedReader
int numberOfInputs = Integer.parseInt(br.readLine());
接下来我想读取数组中的下一行输入
next i want to read next line inputs in an array
int a[] = new int[n];
但我们无法使用此技术阅读
but we cannot read using this technique
for(int i=0;i<n;i++)
{
a[i]=Integer.parseInt(br.readLine()); //won't work
}
所以,有什么解决方案可以解决我的问题或我们不能只使用BufferedReader对象从一行读取多个整数
so , is there any solution of my problem or we can't just read multiple integers from one line using BufferedReader objects
因为使用Scanner对象我们可以读取这种类型的输入
because using Scanner object we can read this type of input
for(int i=0;i<n;i++)
{
a[i]=in.nextInt(); //will work..... 'in' is object of Scanner class
}
plz help
尝试下一步:
int a[] = new int[n];
String line = br.readLine(); // to read multiple integers line
String[] strs = line.trim().split("\\s+");
for (int i = 0; i < n; i++) {
a[i] = Integer.parseInt(strs[i]);
}