格式化为toString()

时间:2017-03-31 18:24:37

标签: java format string-formatting tostring

我是初学者,使用toString()方法返回格式化的String。我正在打印一副卡片,每列都是不同的套装。有没有人有任何想法?这是我的代码:

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()中修改它以使它像那样出来?再次感谢您的时间。

4 个答案:

答案 0 :(得分:1)

您必须创建一个新类别的卡并具有覆盖字符串类

如下所示

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()课程就是为了反映我所做的数字的转变。

答案 1 :(得分:1)

如果你想要实例化一个对象,这是我的解决方案:

Card.java

/*-***************************************************************************
 * Copyright (C) 2017  Miguel Fernandez Fernandez
 *
 * This is free software, licensed under the GNU General Public License v3. 
 * See http://www.gnu.org/licenses/gpl.html for more information.
 ****************************************************************************/

public class Card {

    String suit;
    String rank;

    public Card(String suit, String rank) {
        this.suit = suit;
        this.rank = rank;
    }

    public String getSuit() {
        return suit;
    }

    public void setSuit(String suit) {
        this.suit = suit;
    }

    public String getRank() {
        return rank;
    }

    public void setRank(String rank) {
        this.rank = rank;
    }

    @Override
    public String toString() {
        return rank + "\t" + suit;
    }
}

Main.java

/*-***************************************************************************
 * Copyright (C) 2017  Miguel Fernandez Fernandez
 *
 * This is free software, licensed under the GNU General Public License v3. 
 * See http://www.gnu.org/licenses/gpl.html for more information.
 ****************************************************************************/

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {

    public static void main(String[] args) {

        List<Card> deck = new ArrayList<Card>(52);
        String[] suits = { "Clubs", "Diamonds", "Hearts", "Spades" };
        String[] ranks = { "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace" };

        // Initialize cards
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 13; j++) {
                deck.add(new Card(suits[i], ranks[j]));
            }
        }

        System.out.println("Cards: \n");

        // Print cards
        for (Card c : deck) {
            System.out.println(c.toString());
        }

        System.out.println("\n\nRandom cards...\n\n");

        // Shuffle the cards
        Collections.shuffle(deck);
        System.out.println("Cards: \n");

        // Display the all the cards
        for (Card c : deck) {
            System.out.println(c.toString());
        }
    }
}

谢谢! :)

答案 2 :(得分:0)

以下是制作卡片和甲板课程并打印出整个套牌的示例代码。

class Deck {
    ArrayList<Card> cards = new ArrayList<Card>();
    public Deck() {
        for(int i=0; i < 52; i++ ) {
            cards.add(new Card());
        }
    }

    @Override
    public String toString() {
        String response = "";
        for(int i=0; i<52; i++)
        {
            response = response + "\n" + i+1 + ". Card: " + cards.get(i).toString() ;
        }
        return response;
    }
}

class Card {

    private String suit;
    private String rank;

    @Override
    public String toString() {
        return "It's a " + suit + " " + rank;
    }

    public Card() {
        Random r = new Random();
        int rRank = r.nextInt(12);
        switch(rRank) {
            case 0: {
                this.rank = "Jack";
                break;
            }
            case 1: {
                this.rank = "Queen";
                break;
            }
            case 11: {
                this.rank = "King";
                break;
            }
            case 12: {
                this.rank = "Ace";
                break;
            }
            default: {
                this.rank = rRank + ""; //Don't blame me for it. :D
                break;
            }
        }
        int suit = r.nextInt(3);
        switch(suit) {
            case 0: {
                this.suit = "Club";
                break;
            }
            case 1: {
                this.suit = "Diamond";
                break;
            }
            case 2: {
                this.suit = "Heart";
                break;
            }
            case 3: {
                this.suit = "Spade";
                break;
            }
        }

    }

}


public class Stackoverflow {

    public static void main(String[] args) {
        Deck deck = new Deck();
        System.out.println(deck.toString());
    }

}

答案 3 :(得分:0)

你的随机播放与Fisher-Yates shuffle类似,但并不完全相同,并且不会为你提供所有卡片排列的均匀分布。 (Java附带java.util.Collections类中的Fisher-Yates shuffle。您可以使用Collections.shuffle(list)将对象列表随机排列。

一旦你得到每张卡的套装和等级,你就可以将它们列入一个列表:

    List<Card> cards = new ArrayList<>();

    for (int i = 0; i < 52; i++) {
        String suit = suits[deck[i] / 13];
        String rank = ranks[deck[i] % 13];
        cards.add(new Card(suit, rank));
    }

(您需要从文件顶部的java.util导入这些类。)

import java.util.ArrayList;
import java.util.List;

使用toString方法创建一个Card类:

public class Card {
    private final String suit;
    private final String rank;

    public Card(String suit, String rank) {
        this.suit = suit;
        this.rank = rank;
    }

    public String getSuit() {
        return suit;
    }

    public String getRank() {
        return rank;
    }

    @Override
    public String toString() {
        return rank + " of " + suit;
    }
}

我列出了一些你并不严格需要的东西。这些字段不必是final,但稍后可以使用 immutable 对象。一旦你创建了钻石女王,它就不需要变成另一张卡。一个好的经验法则是,除非确实需要,否则不要让对象变得可变。 (一张可变卡的字段不是final,而且会有字段的设置者,而不仅仅是getter。)我还为字段提供了getter,即使我们还没有在这里使用它们。我在@Override方法中包含了toString注释,这不是绝对必要的,但是如果你打算覆盖一个方法时包含它,编译会警告你,如果你没有,如果我不小心写了tostring而不是toString,可能会发生这种情况。

现在我们已经拥有了cards,我们可以让他们使用toString方法打印出来:

for (Card card : cards) {
    System.out.println(card);
}

最后一点。在您的代码中,您没有正确使用System.out.printf。如果您想在toString方法中使用类似的内容,StringString.format中有相关方法,其使用方式如下:

    @Override
    public String toString() {
        return String.format("%s of %s", rank, suit);
    }

或者,当您打印卡片时,您可以像这样使用它(%n生成换行符):

for (Card card : cards) {
    System.out.printf("Your card is the %s%n", card);
}