大家好,我的程序似乎遇到了问题
示例输入如下:
3 1 2 3
0 1 12
-12
14 1 2 3
5 1 2 3 4 5 6
4 10 20 30 40
示例输出必须是: 第 1 行值的平均值为 2.0
*** Error (line 2): Line is empty - average can't be taken
*** Error (line 3): Header value of 0 - average can't be taken
The average of the values on line 4 is 12.0
*** Error (line 5): Corrupt line - negative header value
*** Error (line 6): Corrupt line - fewer values than header
*** Error (line 7): Corrupt line - extra values on line
The average of the values on line 8 is 25.0
There were 3 valid lines of data
There were 5 corrupt lines of data
这是我到目前为止所拥有的:
public class DataChecker
public static void main(String[] args) throws IOException {
File myFile = new File("numbers.text");
Scanner scanner = new Scanner(myFile);
int count=0,count2=0,sum=0;
int[] val = new int[50];
String line = null;
while (scanner.hasNextLine()) {
line = scanner.nextLine();
Scanner lineScanner = new Scanner(line);
count++;
while(lineScanner.hasNextInt()){
lineScanner.nextInt();
count2++;
}
if(lineScanner.hasNextInt())
val[count2] = lineScanner.nextInt();
for(int i =0;i<count2;i++) {
sum += val[i];
sum = (sum/count2);
System.out.println(sum);
}
System.out.println("There are " + count2 + " numbers on line " + count);
lineScanner.close();
count2=0;
}
scanner.close();
}
感谢任何帮助。
最佳答案
您没有正确统计每行的数字。该算法应该是读取一行,使用扫描仪对其进行标记,然后消耗整数,直到没有更多的整数。跟踪总和以及所看到的整数的数量,然后取这两个和的商以获得平均值。
// your initialization code
int numLines = 0;
while (scanner.hasNextLine()) {
line = scanner.nextLine();
Scanner lineScanner = new Scanner(line);
numLines++;
int count = 0;
int total = 0;
while (lineScanner.hasNextInt()) {
total += lineScanner.nextInt();
++count;
}
if (count == 0) {
System.out.println("Line " + numLines + " has no numbers.");
continue;
}
double avg = 1.0d * total / count;
System.out.println("The average of the values on line " + numLines + " is " + avg);
lineScanner.close();
}
关于java - 查找文件输入的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49744932/