【发布时间】:2015-09-22 17:24:16
【问题描述】:
对于我的编程任务是从文件中读取数据,计算平均值,运行总计,并列出原始数字。我遇到的问题是将数据输出到输出文件中。我不知道如何将控制台上的打印内容打印到输出文件。非常感谢任何帮助!
public static void main(String[] args) throws IOException {
// Declare variables
// Define your file names
final String INPUT_FILE = ("Input.txt");
final String OUTPUT_FILE = ("Output.txt");
int numberOfNumbers = 0; // Number of numbers in the input file
double sum = 0; // The sum of the numbers
double average = 0; // The average of the numbers read
double oneNumber; // An individual number read from the file
double runningTotal = 0; // the running total sum of the numbers
// Access the input/output files
File inputDataFile = new File(INPUT_FILE);
Scanner inputFile = new Scanner(inputDataFile);
FileWriter outputDataFile = new FileWriter(OUTPUT_FILE);
PrintWriter outputFile = new PrintWriter(outputDataFile);
System.out.println("Reading file " + INPUT_FILE + "\r\n" +
"Creating file " + OUTPUT_FILE);
// Read the input file and sum the numbers.
while (inputFile.hasNext()) {
numberOfNumbers++;
oneNumber = inputFile.nextDouble();
sum += oneNumber; // Calculate total sum
runningTotal += oneNumber; // Calculate running total
average = sum / numberOfNumbers; // Calculate the average
System.out.printf("%-10.2f\t %.2f\n", oneNumber, runningTotal);
// 2. write the number and running total to the output file
} // End while
// Add code here to:
// 1. write the number of numbers, the sum and the average
// to the output file using DecimalFormat to format the sum and average
inputFile.close(); // close the input file
outputFile.close(); // close the output file
System.out.println("The sum of the " + numberOfNumbers +
" numbers is " + sum + "\n" +
" and the average is " + average);
System.exit(0);
} // End main
} // End class
【问题讨论】:
标签: java input output text-files