【问题标题】:Convert output into a table将输出转换为表格
【发布时间】:2016-11-22 20:06:14
【问题描述】:

我正在使用这种方法从文本文件中打印一些数据,并尝试将其输出为表格格式。 第一个参数只是请求一个必须在中间列的单词,colSize 应该设置列宽。

public String printTable(String midWord, int colSize) {
    String col1 = "";
    String col2 = midWord;
    String col3 = "";

    System.out.printf( "%-15s %15s %n", col1, midWord, col3);
    //System.out.format ( "%-15s %15s %n", col1, midWord, col3);

    return null;
}

我尝试过同时使用printfSystem.out.format,但它们似乎都在做同样的事情,所以我不确定。

谁能解释我在这种方法中缺少什么。

【问题讨论】:

  • 你能显示文件的内容和解析文件的代码吗?
  • 有什么问题? colSize 在哪里使用?
  • @LaneSurface 我不知道如何使用它...☹️

标签: java format output text-files


【解决方案1】:

您的问题不清楚:您是否尝试读取(文本)文件,知道行由 3 列组成,第二列(因此中间的列)应该是已知的? 使用下面的sn-p,就可以读取文件了:

  1. 一次性打印所有行并逐行打印
  2. 使用扫描仪一个接一个地打印

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Paths;
    import java.util.List;
    import java.util.Scanner;
    import java.util.stream.Stream;
    
    public class TestClass {
       private static final String fileName = "I:/myFile.txt";    
       public static void main(String[] args) {
         Stream<String> lines;
         Scanner scanner;
         try {
             lines = Files.lines(Paths.get(fileName));
             lines.toArray(String[]::new);
             // read all lines
             List<String> readAllLines = Files.readAllLines(Paths.get(fileName));
             // print each of the lines
             readAllLines.forEach(s -> System.out.println(s));
    
             // print a word each time
             File file = new File(fileName);
             scanner = new Scanner(file);
             while (scanner.hasNext()) {
                System.out.println(scanner.next());
             }
    
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }  
      }
    }
    

如果您在放置读取行时遇到问题(每行有 3 个“列”??),请告诉我,我会尽力提供帮助。

【讨论】:

  • 好吧,我正在尝试从文本文件中获取一些数据,然后将其打印到控制台中。但我想对其进行格式化,使其分为三列,中间一列特别是应该在中间显示的一个词
  • 在这里 alvinalexander.com/programming/printf-format-cheat-sheet 你可以找到格式化输出所需的一切:
猜你喜欢
  • 2017-01-10
  • 2019-11-20
  • 2017-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-22
  • 2017-11-19
相关资源
最近更新 更多