Thursday, 15 September 2011

java - How to format string output, so that columns are evenly centered? -



java - How to format string output, so that columns are evenly centered? -

in java class wrote card programme in take "secret card", , @ end tells secret card was. having 1 issue, , formatting output. of right now, when prints fist column 2nd , 3rd not. teacher said utilize spaces, have tried , not work. know there way format unsure. output looks this:

column 0 column 1 column 2 ________________________________________________ 3 of spades 3 of diamonds ace of diamonds 9 of diamonds 2 of diamonds 10 of diamonds ace of spades 10 of hearts king of clubs 6 of clubs 4 of spadesqueen of hearts 5 of diamonds 2 of hearts 7 of clubs 2 of spades jack of diamonds 3 of hearts 5 of hearts 4 of hearts 7 of diamonds

my output code follows:

import java.util.scanner; import java.util.random; public class cardtrick { public static void main(string[] args) { /* declare , initialize variables */ int column = 0, = 0; string name = " "; string playagain = " "; string seedeck = " "; /* declare 52 element array of cards */ card[] deck = new card[52]; /* declare 7 3 array receive cards dealt play trick */ card [][] play = new card[7][3]; /* declare scanner object input */ scanner input = new scanner(system.in);

if want can post entire code, trying not post lot. appreciate help, beingness new java.

i'm going "format" suggestion, mine little different.

in program, you're relying on card's tostring. create formatted in fixed length, , can utilize them anywhere , take same space.

public string tostring() { homecoming string.format( "%5s of %-8s", rank, suit ); }

when print out, you'll have cards aligned on "of" part, think going in first output column.

the "%5s" part right-aligns rank in field 5 characters wide, , "%-8s" part left-aligns suit in field 8 characters wide (which means there additional spaces right if suit shorter 8 characters).

java

No comments:

Post a Comment