Java System.out.println 格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19390687/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 16:45:04  来源:igfitidea点击:

Java System.out.println format

javaprintlnsystem.out

提问by totpiko

I need the system out println to do this format so that the number of whitespaces between the first column and the second column varies based on the content. So the second column is always alligned.

我需要系统 out println 来执行此格式,以便第一列和第二列之间的空格数因内容而异。所以第二列总是对齐的。

Any way to set the second column to start at fixed position?

有什么办法可以将第二列设置为从固定位置开始?

token: accept                        lexical unit: ACCEPT_KEYWORD
token: a                             lexical unit: IDENTIFIER
token .\'n'                          lexical unit: END_OF_INSTRUCTION
token: perform                       lexical unit: PERFORM_KEYWORD
token: find                          lexical unit: IDENTIFIER
token: until                         lexical unit: UNTIL_KEYWORD
token: b                             lexical unit: IDENTIFIER
token: =                             lexical unit: EQUALS_SIGN
token: 0                             lexical unit: INTEGER
token .\n                            lexical unit: END_OF_INSTRUCTION

采纳答案by 4gus71n

Here you have buddy:

你有朋友:

    public class Test {

        public static class Logger {

            private static final int MAX_WHITESPACES = 20;

            public static void s(String token, String lex) {
                String whitespaces = new String(new char[Math.abs(token.length()-MAX_WHITESPACES)]).replace('##代码##', ' ');;
                String line = String.format("token: %s"+whitespaces+"lexical unit: %s", token, lex);
                System.out.println(line);
            }

        }

        public static void main(String[] args) {
            Logger.s("accept","ACCEPT_KEYWORD");
            Logger.s("a","IDENTIFIER");
            Logger.s(".\'n'","END_OF_INSTRUCTION");
            Logger.s("perform","PERFORM_KEYWORD");
        }


    }

Take note that all your tokens must be < MAX_WHITESPACES

请注意,您的所有代币必须 < MAX_WHITESPACES

回答by user1676075

Use String.format()to create a formatted line. For more information.

使用String.format()创建一个格式化的线。 想要查询更多的信息。

Use a width for the token that's the same for all fields, larger than the max token size, and it will line up.

为所有字段使用相同的令牌宽度,大于最大令牌大小,它将对齐。