Lining up outputs in Java

453 Views Asked by At

I am writing a blackjack program that saves user information such as hands won, hands played, and money left for the player, and their name. The outputs should be right justified, even when they are changing. My current code is:

    System.out.format("%s \t \t \t %s %n", "Name:", playerName);
    System.out.format("%s \t \t %d %n", "Hands Played:", playerHands);
    System.out.format("%s \t \t %d %n", "Hands Won:", playerWins);
    System.out.format("%s \t \t \t %.2f %n", "Money:", playerMoney);

This left justifies them in the middle of the screen, but I've run out of ideas for what else to do.

Additional question: why do the 2nd and 3rd print statement only require 2 "\t"s? I assume it has something to do with the length of the strings before them, but is there a hard and fast rule for that?

1

There are 1 best solutions below

2
On

This should help:

System.out.format("%15s  %-15s %n", "Name:", playerName);
System.out.format("%15s  %-15d %n", "Hands Played:", playerHands);
System.out.format("%15s  %-15d %n", "Hands Won:", playerWins);
System.out.format("%15s  %-15.2f %n", "Money:", playerMoney);

Output:

          Name:  Player 1        
  Hands Played:  10              
     Hands Won:  2               
         Money:  15.05