gpt4 book ai didi

java - 从一副牌中洗牌和抽牌

转载 作者:行者123 更新时间:2023-12-01 17:18:22 25 4
gpt4 key购买 nike

我正在尝试创建一个程序,要求用户从一副牌中洗牌或抽牌。它可以编译,但我遇到了一个主要问题:

在打印洗好的牌组或抽一张牌(根据我给出的命令)后,它不允许用户执行其他命令。

任何帮助将不胜感激。

代码如下:

import java.util.Random;
import java.util.Scanner;

public class Deck {

static String [] number = {"Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"};
static String [] suit = {"Clubs", "Hearts", "Diamonds", "Spades"};
static String [] deck = new String[52];
int cardsUsed = 0;

public static void main (String [] args) {
Deck d = new Deck();
// print d.
for (int i = 0; i<number.length; i++) {
for (int j = 0; j<suit.length; j++) {
deck[13*j+i] = number[i] + " of " + suit[j];
}
}

while (true) {
System.out.println ("shuffle or draw");
Scanner s = new Scanner(System.in);
System.out.println ("What would you like to do?");
String command = s.next( );

if (command.equals("shuffle")) {
d.shuffle();
} else if (command.equals("draw")){
d.draw();
}

s.close();
}
}



public void shuffle () {
int k;
Random shuffle = new Random();
for (k = deck.length-1; k >= 0; k--){
int index = Math.abs((shuffle.nextInt())%52);
String temp = deck[k];
deck[k] = deck[index];
deck[index] = temp;
}
int l;
for (l = 0; l<deck.length; l++){
System.out.println (deck[l]);
}
}

public void draw () {
System.out.print (deck[cardsUsed]);

if (cardsUsed < deck.length) {
System.out.print (deck[cardsUsed]);
} else {
System.out.println ("No cards are left in the deck.");
cardsUsed++;
}
}

}

最佳答案

您只能发出一个命令的原因是您正在关闭扫描仪。文档位于 http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#close()表示当您这样做时,它也会关闭底层流。因此,关闭扫描仪后,您将无法再获得任何输入。您应该将扫描仪初始化移到 while 循环之外,并且永远不要关闭它。

关于java - 从一副牌中洗牌和抽牌,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20481442/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com