提问人:pchova 提问时间:2/4/2022 更新时间:2/4/2022 访问量:179
从文件中读取数据后,为什么重新分配局部变量
After reading data from file, why are local variables reassigned
问:
程序要求提供文件的名称。我有一个文件并尝试从中读取数据(仅包含双精度),然后将平均值打印到输出文件。
遍历文件后,我计算并存储平均值,该均值存储在 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: %.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 被标记为重新分配的变量。 mean 被标记为“从未使用分配给 'mean' 的值总和/计数”
答:
1赞
Code-Apprentice
2/4/2022
#1
mean 被标记为“从未使用分配给 'mean' 的值总和/计数”
这正是它所说的。您可以这样做,但从不使用在此计算后分配给的值。看起来你有mean = sum / count;
mean
outputFile.printf("Mean: %.3f\n", mean);
但请记住,Java 是按顺序执行语句的,因此这将始终打印出来。要解决此问题,您需要在将平均值写入文件之前计算平均值。0.000
评论