'After reading data from file, why are local variables reassigned
Program asks for the name of a file. I have a file and trying to read data from it(contains only doubles) and then print the mean to an output file.
After looping through the file, I calculate and store the mean, which is stored in Results.txt. But, my local variables are underlined and my IDE says they are reassigned. Why? They are initialized and within the same method. Everything else in the code works, including the loop. I can't figure out why the mean isn't being sent to the file.
public class FileDemo {
public static void main(String[] args) throws IOException {
double sum = 0;
int count = 0;
double mean = 0; //The average of the numbers
double stdDev = 0; //The standard deviation
// Create an object of type Scanner
Scanner keyboard = new Scanner(System.in);
String filename;
// User input and read file name
System.out.println("This program calculates stats on a file.");
System.out.print("Enter the file name: ");
filename = keyboard.nextLine();
//Create a PrintWriter object passing it the filename Results.txt
//FileWriter f = new FileWriter("Results.txt");
PrintWriter outputFile = new PrintWriter("Results.txt");
//Print the mean and standard deviation to the output file using a three decimal format
outputFile.printf("Mean: %.3f\n", mean);
outputFile.printf("Standard Deviation: %.3f\n", stdDev);
//Close the output file
outputFile.close();
//read from input file
File file2 = new File(filename);
Scanner inputFile = new Scanner(file2);
// Loop until you are at the end of the file
while(inputFile.hasNext()){
double number = inputFile.nextDouble();
sum += number;
count++;
}
inputFile.close();
mean = sum / count;
}
}
sum, count, are flagged as reassigned variables. mean is flagged as 'The value sum / count assigned to 'mean' is never used'
Solution 1:[1]
mean is flagged as 'The value sum / count assigned to 'mean' is never used'
This is exactly what it says. You do mean = sum / count; but you never use the value assigned to mean after this calculation. It looks like you have
outputFile.printf("Mean: %.3f\n", mean);
But remember that Java executes statements in order, so this will always print out 0.000. To fix this, you need to calculate the mean before writing it to the file.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Code-Apprentice |
