我正在努力创建一个“shuffleDeck()”方法。
我想要做的是创建一个方法,它将采用一个数组参数(将是卡片组)洗牌,并返回洗牌数组列表。
这是代码:
class Card
{
int value;
String suit;
String name;
public String toString()
{
return (name + " of " + suit);
}
}
public class PickACard
{
public static void main( String[] args)
{
Card[] deck = buildDeck();
// display Deck(deck);
int chosen = (int)(Math.random()* deck.length);
Card picked = deck[chosen];
System.out.println("You picked a " + picked + " out of the deck.");
System.out.println("In Blackjack your card is worth " + picked.value + " points.");
}
public static Card[] buildDeck()
{
String[] suits = {"clubs", "diamonds", "hearts", "spades" };
String[] names = {"ZERO", "ONE", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "Jack", "Queen", "King", "Ace" };
int i = 0;
Card[] deck = new Card[52];
for ( String s: suits )
{
for ( int v = 2; v<=14; v++)
{
Card c = new Card();
c.suit = s;
c.name = names[v];
if ( v == 14)
c.value = 11;
else if ( v>10)
c.value = 10;
else
c.value = v;
deck[i] = c;
i++;
}
}
return deck;
}
public static String[] shuffleDeck( Card[] deck)
{
/** I have attempted to get two index numbers, and swap them.
I tried to figure out how to loop this so it kind of simulates "shuffling".
*/
}
public static void displayDeck( Card[] deck)
{
for ( Card c: deck)
{
System.out.println(c.value + "\t" + c);
}
}
}
答案 0 :(得分:10)
怎么样:
List<Card> list = Arrays.asList(deck);
Collections.shuffle(list);
答案 1 :(得分:2)
一种方法是将数组转换为列表,并使用java.util.Collections.shuffle(array)
对其进行随机播放:
Card[] deck = ...;
List<Card> list = Arrays.asList(deck);
Collections.shuffle(list);
如果您仍然需要数组而不是List,则可以添加:
list.toArray(deck);
Here is a TIO (Try-it-online) link to see the array to list conversion and shuffling in action.
下面复制的TIO代码作为参考:
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
class M{
public static void main(String[] a){
// Original array
Integer[] array = new Integer[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
System.out.println("before: " + Arrays.toString(array));
// Convert array to list
List<Integer> list = Arrays.asList(array);
// And shuffle that list
Collections.shuffle(list);
System.out.println("after as list: " + list);
// (Optional) then convert the list back to an array,
// and save it in its initial variable (`array` in this case)
list.toArray(array);
System.out.println("after as array: " + Arrays.toString(array));
}
}
答案 2 :(得分:0)
我认为有两种方法可以做到:
- &GT;如果要自己实现方法,可以使用像Fisher-Yates shuffle算法这样的混洗算法。
- &GT;您可以使用shuffle method from Collections
答案 3 :(得分:0)
如果这是针对学校项目的(我认为是这样),可能不允许您使用内置函数,例如Collections :: shuffle()。如果是这种情况,那么你必须尝试模拟随机性(在编程中可能会非常困难)。
创建随机感的最常用方法是使用RNG (random number generator)。 如你所说
我试图获得两个索引号,并交换它们。
正确。一种洗牌的方法是一次挑选一张牌并随机选择另一张牌来交换位置。
使用这些工具,您可以非常轻松地实现自己的随机播放功能。