14

I'm working on a project in which I need to display textual trees. I'm trying to use Java's String.format method to simplify the formatting process, but I ran into trouble when trying to apply variable widths.

Current I have a variable (an int) which is called depth.

I try to do the following:

String.format("%"+depth+"s"," ") + getOriginalText() + "\n";

However I get the following error.

java.util.FormatFlagsConversionMismatchException: Conversion = s, Flags = 0

Any suggestions on how to do this, or should I just settle for loops?

Thanks for the help!

3
  • Are you actually asking this? stackoverflow.com/questions/388461/… Commented Dec 9, 2012 at 6:09
  • Can you post the full code, I'm trying to understand what are you doing. Commented Dec 9, 2012 at 6:14
  • I wondered this also because I knew that C/C++ had a * modifier: The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted., i.e. I was searching for something like String.format( "%*i", pad_width, number ). But the given answer makes sense, too. Commented Jul 27, 2016 at 11:54

2 Answers 2

12

This works:

int depth = 5;
String str= "Hello"+ String.format("%"+depth+"s"," ") + "world" + "\n";
System.out.println(str);

It prints 5 while spaces in between.

Hello     World.

Please check you code and make sure that depth is assigned with a valid int value. Most likely that (invalid value in depth) is the problem.

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

2 Comments

That makes sense. I had a massive lapse in thought I guess. I forgot that I pass zero for depth for the first call, and "%0s" is an error.
@PhillipHuff: Good to know. If you feel, this is helpful then don't forget to accept the answer.
1

You could try the following using "System.out.printf" command:

int depth = 10;

System.out.printf("%s" + "%" +depth + "s", "Hello","World" );

Hello    World

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.