user2904961
user2904961

Reputation:

Formatted Output in Java

I am trying to use formatted output and would like to know how would I use %10s in this code

package formattedoutput;

public class FormattedOutput {

  public static void main(String[] args) {

    double  amount;
    amount = 43.676;
    int spaces;
    spaces = 77;
    String adding; 
    adding = "check me out";



    System.out.printf( "%1.2f%n", amount ); 

    System.out.println();  

    System.out.printf("%12d", spaces );

    System.out.println();

    System.out.printf("%10s", adding );
  }

}

From what I did I don't see any difference it says that "The letter "s" at the end of a format specifier can be used with any type of value. It means that the value should be output in its default format, just as it would be in unformatted output. A number, such as the "10" in %10s can be added to specify the (minimum) number of characters. " Am I using it properly ? If so why it says "s" specifier can be used with any type of value ?

Upvotes: 0

Views: 225

Answers (2)

Warlord
Warlord

Reputation: 2826

%s in formatted output determines, that the value should be printed out as a String, you can use it for numbers or any Object as well, the string value of an Object is determined by calling its toString method. Every object has one.

The number before s, such as %10s determines the minimum number of characters, that will be outputted. If the input string is shorter than the given number of characters, it will be prepended with spaces. This is used for example to align text to the right, such as this:

System.out.printf("%s\n", "id");
System.out.printf("%s\n", "name");
System.out.printf("%s\n", "rank");

outputs

id
name
rank

while

System.out.printf("%5s\n", "id");
System.out.printf("%5s\n", "name");
System.out.printf("%5s\n", "rank");

gives

   id
 name
 rank

Upvotes: 1

Pierre
Pierre

Reputation: 863

%10s tells the formatter to put spaces in front of the String if it is smaller than 10 characters. That's why you see no difference. If you put %15s you ask the formatter to put enough spaces to fill 15 characters with your String, and it will in your example put 3 spaces in front of it.

Upvotes: 0

Related Questions