如何格式化字符串输出java

时间:2017-11-08 02:23:30

标签: java formatting format printf string.format

我创建了一个基本表格,并尝试将表格中的标记格式化为标题。这就是我所拥有的:

Ter Nov  7 23:16:27 BRST 2017 Starting heritrix
Linux userName-VirtualBox 4.10.0-37-generic #41~16.04.1-Ubuntu SMP Fri Oct 6 22:42:59 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
java version "1.8.0_151"
Java(TM) SE Runtime Environment (build 1.8.0_151-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.151-b12, mixed mode)
JAVA_OPTS= -Xmx256m
core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 15623
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 1024
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 15623
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited
Oracle Corporation Java(TM) SE Runtime Environment 1.8.0_151-b12
Exception in thread "main" java.lang.NoClassDefFoundError: sun/security/tools/KeyTool
    at org.archive.crawler.Heritrix.useAdhocKeystore(Heritrix.java:438)
    at org.archive.crawler.Heritrix.instanceMain(Heritrix.java:319)
    at org.archive.crawler.Heritrix.main(Heritrix.java:189)
Caused by: java.lang.ClassNotFoundException: sun.security.tools.KeyTool
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 3 more

这就是我想要的:

NAME TYPE LINE#
a prod 1

我知道System.out.printf()将是格式化我的字符串的理想方式,但这不适用于我在主类中的代码。我创建了一个字符串数组,并使用我创建的.toString方法打印出来(prod 1)。这是我的代码:

NAME TYPE LINE#
a    prod 1

这是我的符号类:

for (int j = 0; j < numOfSym; j++) {
    System.out.println(symbols[j].toString());
}

String.format也不起作用。 printf()是最好的选择吗?任何帮助或链接都会有所帮助。

1 个答案:

答案 0 :(得分:1)

喜欢?

System.out.println("NAME  TYPE  LINE# ");
String[][] data = {{"a", "prod", "1"}, {"b", "prod", "2"}};        

for (int i = 0; i < data.length; i++) {
    System.out.println(String.format("%-5s %-5s %-5s", data[i][0], data[i][1], data[i][2]));
}

或者如果您愿意(在Symbol课程内):

@Override
public String toString() {
    return String.format("%-5s %-5s %-5s", type, name, lineNum);
}