java - Left aligning text in print statements -
this question has answer here:
- align printf output in java 4 answers
i have list of keys , values , print them values left aligned 1 another. instance if map is: {(key9, val9), (key10, val10)}
want print as:
key9: val9 key10: val10
my current solution pretty ugly:
int maxkeylength = findmaxkeylength(mymap); (string key : mymap.keyset()) { int numspaces = maxkeylength - key.size() + 1; // todo: use stringbuilder instead. string toprint = key + ":"; (int = 0;i < numspaces;++i) { toprint += " "; } toprint += mymap.get(key); print(toprint); }
this works bit ugly. question is, there better way this?
you try formatted strings, so
for (string key : mymap.keyset()) { system.out.printf( "%-9s %-15s %n", key+":", mymap.get(key)); }
Comments
Post a Comment