Question

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
Était-ce utile?

La solution

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

Autres conseils

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top