문제

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.

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
도움이 되었습니까?

해결책

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('\0', ' ');;
                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

다른 팁

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

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top