Reputation: 39
I have a text file containing on each line a name and a sequence of integers, for instance
Jules 50 60 40
Ali 45 70 70 90
Emma 45 54
I have this for my code but it does not print out the average also I'm not sure on how to read sequence of integers
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);
}
}
For example the average is a double...
AverageMarks("myfile.txt","Jules")
should print 50.0
AverageMarks("myfile.txt","Ali")
should print 68.75
AverageMarks("myfile.txt","Neil")
should print Neil No such name
Upvotes: 1
Views: 189
Reputation: 4256
Problem is, you should not have else
block in you while
loop. else
block statements should be out of look to make sure that you have processed all the lines in the file and no such name exists. Also there was problem with for
loop index. It should start from 1
not from 0
. Try this:
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);
}
}
Upvotes: 1