Reputation: 57
Create a method called processFile and call it from main passing the name of the file that you created ("scores.rtf"). In processFile, set up the BufferedReader and loop through the file, reading each score. Convert the score to an integer, add them up, and calculate and display the mean. I have done this, and my code runs. The only problem is my code does not calculate the mean. Any idea why?
Here is the code I generated:
import java.io.*;
public class ReadTheCode {
private static double total = 0;
private static int totalLines = 0;
public static void main(String[] args) throws IOException, FileNotFoundException {
String pathToFile = "scores.rtf";
processFile(pathToFile);
}
public static void processFile(String pathToFile) throws IOException, FileNotFoundException {
try(BufferedReader br = new BufferedReader(new FileReader(pathToFile))){
BufferedReader inputReader = new BufferedReader(new InputStreamReader(new FileInputStream(pathToFile)));
String line = br.readLine();
while (line != null) {
double value = Double.parseDouble(line);
total = value + total;
totalLines = totalLines + 1;
System.out.println(value + "%");
line = br.readLine();
}
inputReader.close();
}
}
}
Upvotes: 0
Views: 164
Reputation: 4929
A few things, in your main method, I believe you meant to do this.
String pathToFile = "Scores.txt";
notice it has quotation marks. This makes it a String literal.
Also in your processFile method,
change this line BufferedReader inputReader = new BufferedReader(new InputStreamReader(new FileInputStream(Scores.txt)));
to
BufferedReader inputReader = new BufferedReader(new InputStreamReader(new FileInputStream(pathToFile)));
That way you are referencing the parameter you are passing from your main method.
I also noticed you are referencing 2 variables that you haven't declared anywhere. Total
, and TotalLines
, so I'm not sure if you have showed us all your code or not. If you have showed us all your code, then make sure to declare those variables somewhere. You could simply add this under your public class ReadTheCode {
This will declare and initialize the variables. It will also make them static so you can access them in your static methods. I would recommend that you do look into java naming conventions though, as variables should start with lowercase letters.
private static double Total = 0;
private static int TotalLines = 0;
Upvotes: 2