我需要为我的班级编写一个程序,该程序要求我让程序读取.txt文件中的数据,然后列出每个数字,同时保持这些数字之和的运行总和,平均数字,然后显示他们在控制台上输出到.txt文件。我遇到的问题是格式化输出为表格。我似乎无法弄清楚如何将这些数据转换为两列格式,一个是原始数据,另一个是运行总数。如何在Java中以表格格式输出从.txt文件读取的数据?
这里是我迄今为止在它的那一部分:
import java.util.Scanner;
import java.io.*;
public class SeanPeck_2_04 {
public static void main(String[] args) throws IOException {
// Declare variables
// Define your file names
final String INPUT_FILE = ("/Users/copmuter/Input.txt");
final String OUTPUT_FILE = ("/Users/computer/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 of numbers
runningTotal += oneNumber; // Calculate the running total
System.out.printf("%.2f %.2f", oneNumber, runningTotal, "\n");
2015-09-15
S. Peck