gpt4 book ai didi

java - 从文件中查找输入的平均值

转载 作者:行者123 更新时间:2023-11-30 07:47:32 26 4
gpt4 key购买 nike

大家好,我的程序好像有问题

示例输入如下:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com