Question

I hava a question on the printing Strings. The program should do the following job: get a String as parameter and identify the words and prints them in three columns aligned: Example:

the quick brown fox jumped over the lazy dog

and output should be:

the  quick   brown
fox  jumped  over
the  lazy    dog

My solution was

private void printColumn(String s){
StringTokenizer toker = new StringTokenizer(s);
while (toker.hasMoreTokens()){
    String temp = "";
    for (int i = 0; i < 3; i++){
  temp +=toker.nextToken();
}
    System.out.print(temp);
System.out.println();
}
}

but my output is not aligned

the  quick  brown
fox  jumped  over
the  lazy  dog

any advice please?

Was it helpful?

Solution

Use printf(...) or String.format(...) and add the proper formatting.

Do not add a tab character "\t" after each word.
This solution is bad because if a word is longer than one tab space it would mess up (because it would tab to the next tab space after the word).

Thanks to Hovercraft Full Of Eels for the complete solution.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top