1

以下代码提供了正确的输出,但与我需要的格式不完全相同。

当前代码:

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 循环以反映我想要的输出。

4

3 回答 3

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");
}
于 2013-03-10T23:44:59.083 回答
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();
}
于 2013-03-10T23:46:03.823 回答
1

您需要做的是将每个玩家的输出保存在一个字符串中,然后在内部循环之外打印它。所以像:

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);
    }
于 2013-03-10T23:49:31.613 回答