【问题标题】:How do I output data that is read from a .txt file in tabular format in Java?如何在 Java 中以表格格式输出从 .txt 文件中读取的数据?
【发布时间】: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");

【问题讨论】:

    标签: java input output tabular


    【解决方案1】:

    如果你想在两列中格式化输出,你可以使用

    %-10.2f\t%.2f\n

    注意 -10 是列的大小。

    如果您需要更多示例,请查看

    Is there an easy way to output two columns to the console in Java?

    【讨论】:

    • 谢谢!是的,我检查了那个线程,但仍然无法弄清楚我做错了什么。但这行得通。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多