格式化结果输出字符串

时间:2013-03-10 23:38:45

标签: java

以下代码提供正确的输出,但不完全采用我需要的格式。

当前代码:

public static void main(String[] args)
{
    Scanner scan = new Scanner(System.in);
    Deck deck = new Deck();
    Card C;

    System.out.println(deck.getTotalCards());
    System.out.print("Number of players: ");
    int players = scan.nextInt();
    System.out.print("Number of cards: ");
    int cards = scan.nextInt();

    for(int k=0; k<players; ++k)
    {
        for(int i =0; i<cards; i++)
        {
            C = deck.drawFromDeck();
            System.out.println("Player "+(k+1) + ": " + C.toString());
        }
    }
    scan.close();
}

这提供了此输出:

51 // number of cards in deck

Number of players: 3 //3 - entered by user
Number of cards: 2 // 2- entered by user
Player 1: 4 of Spades
Player 1: Jack of Diamonds
Player 2: 6 of Clubs
Player 2: 2 of Hearts
Player 3: Jack of Clubs
Player 3: 8 of Diamonds

期望的输出:

51
Number of players: 3 //3 - entered by user
Number of cards: 2 // 2- entered by user
Player 1: 4 of Spades, Jack of Diamonds
Player 2: 6 of Clubs, 2 of Hearts
Player 3: Jack of Clubs, 8 of Diamonds

如何改变我的for循环以反映我想要的输出。

3 个答案:

答案 0 :(得分:2)

如果您不想自动打印新行,则需要使用System.out.print()而不是System.out.println()。我认为这样的事情会这样做:

for(int k=0; k<players; ++k)
{
    System.out.print("Player "+(k+1) + ": ");
    for(int i =0; i<cards; i++)
    {
        C = deck.drawFromDeck();
        System.out.print(C.toString());
        if(cards >= 2 && i != cards - 2) {
            System.out.print(", ");
        }
    }
    System.out.print("\n");
}

答案 1 :(得分:1)

在内部循环内,使用System.out.print()代替System.out.println()。在外部循环结束时,调用System.out.println()以在下一行开始下一个输出。

例如:

for (int k = 0; k < players; k++) {
  for (int i = 0; i < cards; i++) {
    if (i == 0) {
      System.out.print("Player "+(k+1) + ": ");
    }
    else {
      System.out.print(",");
    }
    C = deck.drawFromDeck();
    System.out.print(C.toString());
  }
  System.out.println();
}

答案 2 :(得分:1)

您需要做的是将每个播放器的输出保存在String中,然后将其打印在内部循环之外。如下所示:

for(int k=0; k<players; ++k)
    {
        String output = " ";
        for(int i =0; i<cards; i++)
        {
            C = deck.drawFromDeck();
            output+= C.toString() + ",";
        }
        System.out.print("Player " + (k+1) + ": ");
        System.out.println(output);
    }