Lal*_*mar 4 java arrays buffer integer bufferedreader
我正在使用BufferedReader类来读取我的Java程序中的输入.我想读取用户输入的输入,用户可以用空格单行输入多个整数数据.我想在整数数组中读取所有这些数据.
输入格式 - 用户首先输入他/她想要输入的数量
然后在下一行中有多个整数值 -
INPUT:
五
2 456 43 21 12
现在,我使用BufferedReader的对象(br)读取输入
int numberOfInputs = Integer.parseInt(br.readLine());
Run Code Online (Sandbox Code Playgroud)
接下来,我想读取数组中的下一行输入
int a[] = new int[n];
Run Code Online (Sandbox Code Playgroud)
但我们无法阅读使用这种技术
for(int i=0;i<n;i++)
{
a[i]=Integer.parseInt(br.readLine()); //won't work
}
Run Code Online (Sandbox Code Playgroud)
那么,我的问题是否有任何解决方案,或者我们不能使用BufferedReader对象从一行读取多个整数
因为使用Scanner对象我们可以读取这种类型的输入
for(int i=0;i<n;i++)
{
a[i]=in.nextInt(); //will work..... 'in' is object of Scanner class
}
Run Code Online (Sandbox Code Playgroud)
Pau*_*gas 13
尝试下一个:
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]);
}
Run Code Online (Sandbox Code Playgroud)
迟到了,但您可以在 Java 8 中使用streams.
InputStreamReader isr= new InputStreamReader();
BufferedReader br= new BufferedReader(isr);
int[] input = Arrays.stream(br.readLine().split("\\s+")).mapToInt(Integer::parseInt).toArray();
Run Code Online (Sandbox Code Playgroud)
如果你想读取整数而你不知道整数的数量
String[] integersInString = br.readLine().split(" ");
int a[] = new int[integersInString.length];
for (int i = 0; i < integersInString.length; i++) {
a[i] = Integer.parseInt(integersInString[i]);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
39775 次 |
| 最近记录: |