In my java class we wrote a card program in which you choose a "secret card", and at the end it tells you what your secret card was. I am only having one issue, and that is formatting the output. As of right now, when it prints the fist column is even but the 2nd and 3rd are not. My teacher said to use spaces, but I have tried this and does not work. I know there is a way to format it but am unsure. The output looks like 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 is as follows:
import java.util.Scanner;
import java.util.Random;
public class CardTrick {
public static void main(String[] args) {
/* declare and initialize variables */
int column = 0, i = 0;
String name = " ";
String playAgain = " ";
String seeDeck = " ";
/* Declare a 52 element array of cards */
Card[] deck = new Card[52];
/* Declare a 7 by 3 array to receive the cards dealt to play the trick */
Card [][] play = new Card[7][3];
/* Declare a Scanner object for input */
Scanner input = new Scanner(System.in);
If you want I can post the entire code, but I was trying not to post a lot. I greatly appreciate any help, being I am new to Java.
I'm also going with the "format" suggestion, but mine is a little different.
In your program, you're relying on your card's toString
. So make that formatted in a fixed length, and then you can use them anywhere and they will take up the same space.
public String toString() {
return String.format( "%5s of %-8s", rank, suit );
}
When you print this out, you'll have all your cards aligned on the "of" part, which I think is what you were going for in your first output column.
The "%5s" part right-aligns the rank in a field 5 characters wide, and the "%-8s" part left-aligns the suit in a field 8 characters wide (which means there are additional spaces to the right if the suit is shorter than 8 characters).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With