1

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?

1
  • 2
    You need to know the maximum width of each column and pad enough spaces beyond it. Something like this (first half of the answer) demonstrates the basic idea Commented Jun 18, 2013 at 2:29

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.