我初學者使用toString()方法返回格式化的字符串。我打印一副撲克牌,每列都是不同的套裝。有沒有人有任何想法?下面是我的代碼有:格式化toString()
public class DeckOfCards {
public static void main(String[] args) {
int[] deck = new int[52];
//String[] suits = {"Spades", "Hearts", "Diamonds", "Clubs"};
String[] suits = {"Clubs","Diamonds","Hearts","Spades"};
//String[] ranks = {"Ace","King", "Queen", "Jack", "10", "9", "8", "7", "6", "5", "4", "3", "2"};
String[] ranks = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King","Ace"};
// Initialize cards
for (int i = 0; i < deck.length; i++) {
deck[i] = i;
}
// Shuffle the cards
for (int i = 0; i < deck.length; i++) {
int index = (int)(Math.random() * deck.length);
int temp = deck[i];
deck[i] = deck[index];
deck[index] = temp;
}
// Display the all the cards
for (int i = 0; i < 52; i++) {
String suit = suits[deck[i]/13];
String rank = ranks[deck[i] % 13];
System.out.println(rank + " of " + suit);
}
System.out.println("------------------------------");
for(int i=0;i<deck.length;i++){
for(int j=i;j<deck.length;j++){
if(deck[j]==51-i){
int temp = deck[i];
deck[i] = deck[j];
deck[j] = temp;
}
}
}
// Display the all the cards
for (int i = 0; i < 52; i++) {
String suit = suits[deck[i]/13];
String rank = ranks[deck[i] % 13];
System.out.printf(rank + " of " + suit + "\t");
}
}
}
我相信會在toString()方法的主要領域是在這裏:
// Display the all the cards
for (int i = 0; i < 52; i++) {
String suit = suits[deck[i]/13];
String rank = ranks[deck[i] % 13];
System.out.println(rank + " of " + suit);
}
我怎麼會在toString()方法使用,也實例一個可以打印這個toString()方法的對象?感謝您的時間。因此,它依次顯示在橋的比賽,我想輸出的是這樣的:
Ace of Spades Ace of Hearts Ace of Diamonds Ace of Clubs
...
// And so on until it reaches two of clubs
做這些方式打印它像這樣沒有一個是多餘的間隔,或者如果沒有什麼可以在被修改toString()讓它出來呢?再次感謝您的時間。