java - 从java数组中获取五个随机元素
问题描述
我已经在这个项目上工作了几天,我能够完成大部分工作,但我一直在努力从我的阵列中取出五个不同的项目。我可以选择五次相同的项目。
这是我的代码的样子:
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
我现在所拥有的工作,但不正确。
解决方案
在阅读源代码时,我编写了新代码来增加您的歧义。因此,我在某些行中添加了注释以清楚地理解。
public class CardGuessingGame {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
//list of cards
List<String> myCards = Arrays.asList("two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "jack", "queen", "king", "ace");
//shuffle cards
Collections.shuffle(myCards);
//get first 5 elements from shuffled list
HashSet<String> myHand = new HashSet<>();
for (int i = 0; i < 5; i++) {
myHand.add(myCards.get(i));
System.out.println(myCards.get(i));
}
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 set contains , you found the card
if (myHand.contains(s)) {
System.out.println("I have that card in my hand");
} else {
System.out.println("I do not have that card in hand!");
}
System.out.print("These are the cards which is in my hand: ");
//write all cards in my hand with sepearete comma
System.out.println(String.join(",", myHand));
}
}