我是使用 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() 中修改什么来让它像这样打印出来?再次感谢您的宝贵时间。
最佳答案
您必须创建一个新的卡片类并拥有一个覆盖的字符串类
如下所示
public class Cards {
private int numb;
private int suite;
public Cards(int suite, int numb) {
this.numb = numb;
this.suite = suite;
}
public int getNumb() {
if (numb == 0){
return 11;
}
if (numb >= 9 && numb <=12){
return 10;
}
return numb + 1;
}
@Override
public String toString() {
String arbNumb = null;
String arbSuite = null;
switch (suite){
case 0:
arbSuite = "Heart";
break;
case 1:
arbSuite = "Diamond";
break;
case 2:
arbSuite = "Spades";
break;
case 3:
arbSuite = "Clubs";
break;
}
switch (numb){
case 0:
arbNumb = "Ace";
break;
case 10:
arbNumb = "Jack";
break;
case 11:
arbNumb = "Queen";
break;
case 12:
arbNumb = "King";
break;
}
if (numb > 0 && numb < 10){
arbNumb = String.valueOf(numb+1);
}
return arbNumb + " of " + arbSuite;
}
}
这意味着当你实例化Cards
类时,当你调用yourInstanceOfClass.toString
时,数字将被转换为相应的字符串。您可以对套房和号码进行此操作。
我分配的数字正是我的做法,但您当然可以根据自己的喜好更改它们。
getNumb()
类只是用来反射(reflect)我所做的数字的变化。
关于java - 格式化为String(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43147314/