从文件中读取数据后,为什么要重新分配局部变量



程序询问文件名。我有一个文件,试图从中读取数据(只包含双精度(,然后将平均值打印到输出文件中。

在循环浏览该文件后,我计算并存储均值,该均值存储在Results.txt中。但是,我的局部变量带有下划线,IDE表示它们已重新分配。为什么?它们在同一方法中初始化。代码中的其他一切都能正常工作,包括循环。我不明白为什么没有把平均值发送到文件中。

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: %.3fn", mean);
outputFile.printf("Standard Deviation: %.3fn", 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被标记为重新分配的变量。mean标记为"分配给‘mean’的值总和/计数从未使用">

mean标记为"分配给'mean'的值总和/计数从未使用">

这正是它所说的。您执行mean = sum / count;,但在此计算之后永远不会使用分配给mean的值。看起来你有

outputFile.printf("Mean: %.3fn", mean);

但请记住,Java按顺序执行语句,因此它将始终打印出0.000。要解决此问题,您需要在将平均值写入文件之前计算

最新更新