【发布时间】:2018-09-12 22:35:50
【问题描述】:
我已经在这个项目上工作了几天,我能够完成大部分工作,但我一直在努力从我的阵列中取出五个不同的项目。我可以选择五次相同的项目。
我的代码如下所示:
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
我现在拥有的东西可以工作,但不正确。
【问题讨论】:
-
工作但不正确,所以换句话说它不工作:)
-
您只选择一个
cardInHand,然后在for循环中使用randomNums打印单个cardInHand。 -
你有没有试过和你的导师或助教一起复习你的工作?这里的人可能会向您展示工作代码,但您可以通过对话了解您可能遗漏或误用的概念。
-
pjs,今天和我的教授交谈并让他查看代码,他指出我应该使用循环,因为我有 5 个打印语句(不是这个程序的主要问题,但是无论如何修复了那部分。)试图指出我的程序发生了什么,但他并没有真正帮助,这就是我在堆栈上的原因。
-
如果要保证不同的卡,可以考虑使用Collections.shuffle。然后遍历洗牌列表以获得所需数量的项目。如果您使用随机选择,即使您更正了当前仅调用
nextInt一次的错误,您也可以获得重复。顺便说一句,如果您希望用户看到您的评论,请在他们的用户名前加上“@”,例如“@pjs”。