3 回答
TA贡献1848条经验 获得超2个赞
这是一个有效的代码,只需要独特的卡片。首先,您应该知道哪些变量是数组,哪些不是。
调用rand.nextInt(13);不会将 Random 实例设置为生成 1 到 13 之间的随机数,但实际上会生成一个。
你的随机数生成应该放在循环中。手中的卡片需要包含多个值,因此应使用数组。
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
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
String[] cardsInHand = new String[5];
List<String> cards = new LinkedList<>(Arrays.asList(myCards));
Collections.shuffle(cards);
for (int i = 0; i < 5; i++) {
//This will not give you unique cards!
//int randomNums = rand.nextInt(myCards.length); // Randomizes "randomNums to the length of the array"
cardsInHand[i] = cards.remove(0);
}
System.out.println(Arrays.toString(cardsInHand));
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
//Some kind of contains method. You can traverse the array use a list or do however you like
Arrays.sort(cardsInHand);
if (Arrays.binarySearch(cardsInHand,s) >= 0) {
System.out.println("I do have that card in hand");
} else {
System.out.println("I do not have that card in hand!");
}
//Close the stream
answer.close();
System.out.print("These were the cards I had in hand: ");
System.out.println(Arrays.toString(cardsInHand));
}
}
添加回答
举报