BufferedReader 并填充一个 int 数组
BufferedReader and filling an int array
我有一个作业遇到了一些问题。
该程序使用 Buffered Reader,在之前的作业中,我们总是将用户输入放在一行上,然后使用 .split("\s+")
将其拆分。此赋值在单独的一行中接受 最多 500 个整数,直到它达到 null。
我的问题是将 String 输入解析为 int 数组。通常我有一个设置为 inputValue.split("\s+")
的字符串数组,但教授说我们只需要一个数组(我们的 int 数组),如果不以某种方式拆分输入我无法弄清楚,因为现在我是没有将所有输入都输入到我的 int 数组中。
int count = 0;
int intScoresArr[] = new int [500];
//String strArray[];
while((inputValues = BR.readLine()) != null) {
for(int i = 0; i < inputValues.length(); i++) {
intScoresArr[i] = Integer.parseInt(strArray[i]);
count++;
}
}
average = calcMean(intScoresArr, count);
System.out.println(NF.format(average));
这是一些输入和我对输出的期望以及当我遍历并打印出数组时我实际得到的。
input:
1
2
3
4
5
output:
count: 5
intScouresArr = 5 0 0 0 0
expected output:
count: 5
intScoresArr = 1 2 3 4 5
如果您希望每行有一个整数,则不需要两个嵌套循环;外面的 while
就够了:
int count = 0;
int intScoresArr[] = new int [500];
String line;
while((line = BR.readLine()) != null) {
intScoresArr[count] = Integer.parseInt(line.trim());
count++;
}
我有一个作业遇到了一些问题。
该程序使用 Buffered Reader,在之前的作业中,我们总是将用户输入放在一行上,然后使用 .split("\s+")
将其拆分。此赋值在单独的一行中接受 最多 500 个整数,直到它达到 null。
我的问题是将 String 输入解析为 int 数组。通常我有一个设置为 inputValue.split("\s+")
的字符串数组,但教授说我们只需要一个数组(我们的 int 数组),如果不以某种方式拆分输入我无法弄清楚,因为现在我是没有将所有输入都输入到我的 int 数组中。
int count = 0;
int intScoresArr[] = new int [500];
//String strArray[];
while((inputValues = BR.readLine()) != null) {
for(int i = 0; i < inputValues.length(); i++) {
intScoresArr[i] = Integer.parseInt(strArray[i]);
count++;
}
}
average = calcMean(intScoresArr, count);
System.out.println(NF.format(average));
这是一些输入和我对输出的期望以及当我遍历并打印出数组时我实际得到的。
input:
1
2
3
4
5
output:
count: 5
intScouresArr = 5 0 0 0 0
expected output:
count: 5
intScoresArr = 1 2 3 4 5
如果您希望每行有一个整数,则不需要两个嵌套循环;外面的 while
就够了:
int count = 0;
int intScoresArr[] = new int [500];
String line;
while((line = BR.readLine()) != null) {
intScoresArr[count] = Integer.parseInt(line.trim());
count++;
}