System.out.print。如何让打印输出进行编号? (Java)

System.out.print . How do you get the printed output to be numbered? (Java)

所以假设我要打印出 500 名员工的庞大记录。在打印出记录后,我希望它看起来像:

   1. Matthew J. $USD 28.404
   2. Donna M. $USD 43.254
   3. Jordan D. $USD 15.532
   4.
   5. 
   6.
   7. and so on......

但是...使用正常的打印输出命令看起来像:

System.out.println();

我的输出:

   Matthew J. $USD 28.404
   Donna M. $USD 43.254
   Jordan D. $USD 15.532



   and so on......

编辑:那么如何让输出对每一行进行编号?

后期编辑

我的 System.out.print 正在从列表中打印出信息(来自 JSON,所有这些都已解决,感谢 Prasad Khode)这是我的代码:

for (Manager iterator : managersList) {

    System.out.println(iterator.getName() + " - " + iterator.getSalary());
}

这会打印出

Name - Salary

如何打印:

1. Name - Salary
2. Name - Salary

等等。 一个解决方案将非常感激。谢谢。

如果您使用 for 循环打印记录,那么您可以使用

System.out.println((i+1)+". "+ record[i]);
int i = 1;
while(something) {
    println(i + "." + SomeName);
    i++
}

这是您要找的吗?

修改System.out.println()使其输出行号不是一件容易的事。您可以创建一个新的 PrintStream subclass(这就是 out),覆盖 PrintStream 中的所有适当方法,以便 println(boolean)println(char)println(long)等等都打印出开头的行号(在 class 本身中维护)。然后,创建它指向 System.out 并以某种方式将 System.out 重新附加到此 PrintStream。这并非不可能,对于想要在 System 内部乱搞的人来说可能是一项值得做的事情,但是有数量 种更简单的方法可以做到这一点。

首先,考虑将整个流打印出来,然后通过 awk 或某些类似程序将其通过管道传输。轻松多了,不会乱来。

假设您确实想进入 "this needs to be the output from Java",让我们创建一个包装器 class。

package com.michaelt.so.outwrapper;

import java.io.PrintStream;

public class Wrapper {
    static PrintStream out = System.out;
    static int lineNum = 1;

    static void println(String arg) {
        out.println((lineNum++) + ". " + arg);
    }

    static void printlnFancy(String arg) {
        out.printf("%3d. %s\n", lineNum++, arg);
    }
}

然后使用:

package com.michaelt.so.outwrapper;

public class Main {
    public static void main(String[] args) {
        for(char c = 'a'; c <= 'f'; c++) {
            Wrapper.println(""+c); // I just want a string
        }

        for(char c = 'A'; c <= 'F'; c++) {
            Wrapper.printlnFancy(""+c);
        }
    }
}

打印出:

1. a
2. b
3. c
4. d
5. e
6. f
  7. A
  8. B
  9. C
 10. D
 11. E
 12. F

我并不是说这是一件好事。它涉及将所有 System.out.println() 更改为 Wrapper class... 但它实际上并没有与 System.out 混淆,这可能会导致令人惊讶的事情。