我想显示不同的字符串数组元素:
CardGame.java:
public class CardGame {
public static void main(String[] args){
String[] suit = { "Clubs", "Hearts", "Diamonds", "Spades" };
String[] deck = { "2", "3", "4", "5", "6", "7", "8", "9", "10",
"Jack", "Queen", "King", "Aces" };
int i = (int) ( Math.random() * deck.length );
int j = (int) ( Math.random() * suit.length );
for( int a = 0; a < 7; a++ ) {
System.out.println( "Deck " + deck[i] + " Suit " + suit[j] );
}
System.out.println();
}
}
我将如何做?指出我正确显示那些不同元素的逻辑。感谢。
答案 0 :(得分:3)
把
int i = (int) ( Math.random() * deck.length );
int j = (int) ( Math.random() * suit.length );
进入for
循环,以便在每次迭代中生成一个新的随机卡
答案 1 :(得分:2)
int times = 10; // Say you want it 10 times, in your code it's 7.
for (int i = 0; i < times; i++) {
System.out.println(deck[(int) (Math.random() * deck.length)]
+ " : " + suit[(int) (Math.random() * suit.length)]);
}
答案 2 :(得分:0)
public class CardGame {
public static void main(String[] args) {
String[] deck = { "Clubs", "Hearts", "Diamonds", "Spades" };
String[] suit = { "2", "3", "4", "5", "6", "7", "8", "9", "10",
"Jack", "Queen", "King", "Aces" };
for( int a = 0; a < 7; a++ ) {
int i = (int) ( Math.random() * deck.length );
int j = (int) ( Math.random() * suit.length );
System.out.println( "Deck " + deck[i] + " Suit " + suit[j] );
}
System.out.println();
}
}
答案 3 :(得分:0)
import java.util.HashSet;
import java.util.Set;
public class CardGame {
public static void main(String[] args){
String[] deck = { "Clubs", "Hearts", "Diamonds", "Spades" };
String[] suit = { "2", "3", "4", "5", "6", "7", "8", "9", "10",
"Jack", "Queen", "King", "Aces" };
Set<String> s = new HashSet<String>();
int totalCards=0;
while(s.size() < (deck.length * suit.length)){
int i = (int) ( Math.random() * deck.length );
int j = (int) ( Math.random() * suit.length );
if(!s.contains("Deck " + deck[i] + " Suit " + suit[j])){
s.add("Deck " + deck[i] + " Suit " + suit[j]);
totalCards++;
}
}
System.out.println("Cards at Random: ");
for(String str: s)
System.out.println(str);
System.out.println("Total Cards: "+ totalCards);
}
}
这将随机返回所有52张卡(所有组合)
答案 4 :(得分:0)
我不太明白你的问题 - 如果你想要很多随机卡片,或者所有这些卡片。
所有这些:
for (String cardSuit: suit) {
for (String cardDeck: deck) {
System.out.println(cardDeck + " " + cardSuit);
}
}
随机(给定数字):
Random rnd = new java.util.Random();
for (int i = 0; i < number; i++) {
String cardSuit = suit[rnd.nextInt(suit.length)],
cardDeck = deck[rnd.nextInt(deck.length)];
System.out.println(cardDeck + " " + cardSuit);
}
答案 5 :(得分:0)
int i = (int) ( Math.random() * deck.length );
int j = (int) ( Math.random() * suit.length );
进入for循环,因为你的新生成i j值得到