我有一个文本文件,每行包含一个名称和一个整数序列,例如
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
答案 0 :(得分:1)
问题是,您else
循环中不应该while
阻止。 else
块语句应该不在考虑以确保您已经处理了文件中的所有行,并且不存在这样的名称。 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);
}
}