我已经在这个项目上工作了几天,我能够完成大部分工作,但我一直在努力从我的阵列中取出五个不同的项目。不过,我可以选择相同的项目五次。
这是我的代码的样子:
public class CardGuessingGame {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String[] myCards = new String[]{"two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "jack", "queen", "king", "ace"}; // Array for cards
Random rand = new Random(); //random construction
rand.nextInt(13); // Sets rand to 0-12 int
//int randomNums = rand.nextInt(13); // sets randNums from 0-12
int randomNums = rand.nextInt(myCards.length); //Randomizes "randomNums to the length of the array"
String cardInHand = myCards[(int)randomNums];
for (randomNums=0; randomNums < 5; randomNums++) {
System.out.println(cardInHand);
}
System.out.print("Guess the card in my hand: "); // Prints to user asking for guess
Scanner answer = new Scanner(System.in); // gets user input
String s = answer.nextLine(); //stores user input inside variable s
if(s.equals(cardInHand)) {
System.out.println("I do have that card in hand");
} else {
System.out.println("I do not have that card in hand!");
}
System.out.print("These were the cards I had in hand: ");
System.out.println(cardInHand);
}
}
这是输出
run:
four
four
four
four
four
Guess the card in my hand: four
I do have that card in hand
These were the cards I had in hand: four
我现在所拥有的有效,但不正确。
我认为您对 rand.nextInt(13) 的作用有误解。在这里,您正确地创建了随机对象,但是在第二行中,您认为将 rand 设置为 0-12,而实际上它只是调用一个方法来返回一个 0-12 之间的随机整数,并且完全不做任何事情。
Random rand = new Random(); //random construction
rand.nextInt(13); // Sets rand to 0-12 int
一种。您将变量 randomNums 设置为某个随机值,我不知道为什么,当您在任何可能的使用之前在 for 循环中将其重置为零时。
湾 您存储卡片的一般方法是不正确的,因为您应该制作一个新的 ArrayList 来存储 5 张卡片,但实际上,您只生成了一张卡片并打印了 5 次
int randomNums = rand.nextInt(myCards.length);
String cardInHand = myCards[(int)randomNums];
for (randomNums=0; randomNums < 5; randomNums++) {
System.out.println(cardInHand);
}
这就是代码的更清晰、更合乎逻辑的版本应该是什么样子。
String[] myCards = {"two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "jack", "queen", "king", "ace"};
Random rand = new Random();
Scanner scan = new Scanner(System.in);
int cardIndex = rand.nextInt(myCards.length);
ArrayList<String> playerHand = new ArrayList<>();
for (int i = 0; i < 5; i++) {
while (playerHand.contains(myCards[cardIndex]))
cardIndex = rand.nextInt(myCards.length);
playerHand.add(myCards[cardIndex]);
}
System.out.print("Guess the card in my hand: ");
if(playerHand.contains(scan.nextLine()))
System.out.println("I do have that card in hand");
else
System.out.println("I do not have that card in hand!");
System.out.print("These were the cards I had in hand: ");
System.out.println(playerHand);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句