【问题标题】:Console output in a matrix format矩阵格式的控制台输出
【发布时间】:2018-05-05 08:42:29
【问题描述】:
public class dataarrange {
    public static void main(String args[]) {
        try {
            PrintStream myconsole = new PrintStream(new File("D://out.txt"));
            for (int i = 0; i < 10; i++) {
                double a = Math.sqrt(i);
                int b = 10 + 5;
                double c = Math.cos(i);
                myconsole.print(a);
                myconsole.print(b);
                myconsole.print(c);
            }
        } catch (FileNotFoundException ex) {
            System.out.println(ex);
        }
    }
}

在这个编程代码中,我生成了一个名为out 的文本文件,我在其中写下了dataarrange class. 的输出代码没有错误。根据代码,我们得到 a,b,c 10 次。我在文本文件中系统地记下该值。文本文件应该看起来像一个有 10 行和 3 列的矩阵。但是当我打开文本文件 out.txt 时,所有数据都是分散的。它们被写成一行而不是矩阵格式。

期望的输出:

a    b    c

val1 val2 val3

val4 val5 val6

val7 val8 val9

等等……

但是得到输出val1 val2 val3 val4 val5 val6。我该如何解决这个问题?

【问题讨论】:

  • String.format - 可能类似于 this for example, example
  • documentation - println() 用于跳到下一行,更好的是printf(...) 用于格式化和打印(这是String.formatprint
  • 是否需要对齐所有列?或者只是打印它们之间有空格?
  • 请遵守命名约定。类名应始终以大写字符开头,然后是驼峰式。所以改为DataRange

标签: java file tabular printstream


【解决方案1】:

在 for 循环中使用它会对齐列:

 double a = Math.sqrt(i);
 int b=10+5;
 double c=Math.cos(i);
 myconsole.printf("%10f %10d %10f", a, b, c);
 myconsole.println();

输出:

  0.000000         15   1.000000
  1.000000         15   0.540302
  1.414214         15  -0.416147
  1.732051         15  -0.989992
  2.000000         15  -0.653644
  2.236068         15   0.283662
  2.449490         15   0.960170
  2.645751         15   0.753902
  2.828427         15  -0.145500
  3.000000         15  -0.911130

【讨论】:

  • 当您可以将%n 添加到格式字符串的末尾(即myconsole.printf("%10f %10d %10f%n", a, b, c);)时,为什么要单独调用println
  • 当然。在一个语句中间隔列并在末尾添加换行符对我来说更具可读性。不过使用%n 更简洁。
【解决方案2】:

您也可以使用转义序列 \n \t 但上面带有格式化字符串的 anwser 应该是首选

封装测试;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;

public class DataRange {
    public static void main(String args[]) {

        try {
            PrintStream myconsole = new PrintStream(new File("out.txt"));
            for (int i = 0; i < 10; i++) {
                double a = Math.sqrt(i);

                int b = 10 + 5;
                double c = Math.cos(i);
                System.out.print("\t" + a);
                myconsole.print("\t" + a);
                System.out.print("\t" + b);
                myconsole.print("\t" + b);
                System.out.print("\t" + c);
                myconsole.print("\t" + c);
                myconsole.print("\n");
                System.out.println("\n");
                System.out.println("Completed");
            }
        } catch (FileNotFoundException ex) {
            System.out.println(ex);
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-19
    • 2010-11-29
    • 1970-01-01
    • 1970-01-01
    • 2021-12-02
    • 2017-11-22
    • 2014-05-14
    相关资源
    最近更新 更多