【发布时间】:2015-09-15 23:29:51
【问题描述】:
我需要为我的班级编写一个程序,该程序需要我让程序从 .txt 文件中读取数据,然后列出每个数字,同时保持这些数字总和的运行总和,将数字平均,然后在控制台上显示它们并将它们输出到 .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");
【问题讨论】: