1

I am working on an application that requires me to change the number of spaces dynamically. Every time i need to increase the spaces by one. I know the logic behind it, but I couldn't find any documentation to help with the syntax.

System.out.printf("%3s", " ");

the code above is inside a nested loop, I would like the number 3 to be dynamic. the number needs to be a variable in order to accomplish what I need it to do. how can I set the number before s to a variable?

3 Answers 3

5

Like:

int gap = 3;

System.out.printf("%" + gap + "s", " ");
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I though everything had to be in double quotes in order to work.
0
String space = ""

for(int i = 0; i < 5; i++){
    space += " ";
    System.out.printf("%s", i + space + ",");
}

Comments

0

In, formating print output, Format specifiers begin with a percent sign (%) and end with a converter(s). The converter is a character indicating the type of argument to be formatted. In between the percent sign (%) and the converter you can have optional flags and specifiers(width, precision, sign).

long n = 461012;
System.out.format("%08d%n", n); // prints "00461012"

in the above example:

  1. d is a converter specifying our target parameter n to be printed as decimal integer.
  2. 08 is a flag: specifying the printed decimal integer should be eight characters in width, with leading zeroes as necessary.

Check the documentation : Class Formatter and Formatting Numeric Print Output

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.