gpt4 book ai didi

java - 读取文件并打印字符串和整数的平均值

转载 作者:行者123 更新时间:2023-11-30 07:27:05 28 4
gpt4 key购买 nike

例如,我有一个文本文件,每行包含一个名称和一个整数序列

Jules 50 60 40
Ali 45 70 70 90
Emma 45 54

我的代码有这个,但它不会打印出平均值,我也不确定如何读取整数序列

   public void AverageMarks(String fName, String pname) {

BufferedReader br = null;
try{
br = new BufferedReader(new FileReader(fName));
}catch(FileNotFoundException e){
System.out.println("Could not find file");
}

try{
double average = 0;
double sum = 0;
String line;

while((line = br.readLine()) != null){
String[] lines = line.split(" ");

if(pname.equals(lines[0])){
for(int i =0; i<lines.length; i++){
sum+= Double.parseDouble(lines[i+1]);
}
average = sum / lines.length;
System.out.println(average);
System.exit(0);
}
else{
System.out.println(pname + " No such name");
System.exit(0);
}
}

}catch(IOException e){
System.out.println("An error has occured");
}
finally{
System.exit(0);
}
}

例如平均值是双倍...

  • AverageMarks("myfile.txt","Jules") 应打印 50.0
  • AverageMarks("myfile.txt","Ali") 应打印 68.75
  • AverageMarks("myfile.txt","Neil") 应该打印 Neil No such name

最佳答案

问题是,您的 while 循环中不应该有 else block 。 else block 语句应该不显眼,以确保您已处理文件中的所有行并且不存在此类名称。 for 循环索引也存在问题。它应该从 1 开始,而不是从 0 开始。试试这个:

public void AverageMarks(String fName, String pname) {

BufferedReader br = null;
try{
br = new BufferedReader(new FileReader(fName));
}catch(FileNotFoundException e){
System.out.println("Could not find file");
}

try{
double average = 0;
double sum = 0;
String line;

while((line = br.readLine()) != null){
String[] lines = line.split(" ");

if(pname.equals(lines[0])){
if(lines.length > 1) { // check to calculate average only when there are numbers as well in the line
for(int i = 1; i<lines.length; i++){ // loop index shold start from 1 as element at index 0 is name
sum+= Double.parseDouble(lines[i]);
}

average = sum / (lines.length - 1);
}
System.out.println(average);
System.exit(0);
}
}

// moved these lines from inside loop, to make sure all the names in the files have been checked
System.out.println(pname + " No such name");
System.exit(0);

}catch(IOException e){
System.out.println("An error has occured");
}
finally{
System.exit(0);
}
}

关于java - 读取文件并打印字符串和整数的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36678330/

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