5 回答

TA貢獻(xiàn)1785條經(jīng)驗(yàn) 獲得超4個(gè)贊
讓您randomInt()返回?cái)?shù)字并調(diào)用 中的函數(shù)shuffle()。
private static void shuffle(Card[] cardArray) {
for (int i = 1; i <= 20; i++) {
int a = randomInt();
int b = randomInt();
Card temp = cardArray[a];
cardArray[a] = cardArray[b];
cardArray[b] = temp;
}
}
private static int randomInt() {
return (int)(Math.random() * 12);
}
這將根據(jù)randomInt()生成索引的方式洗牌你的牌組

TA貢獻(xiàn)1872條經(jīng)驗(yàn) 獲得超4個(gè)贊
你可以創(chuàng)建一個(gè) Deck 類并將你的邏輯和數(shù)據(jù)放在這個(gè)類中
public class Deck {
private Card[] deck = new Card[52];
public Deck(){
initDeck();
}
public void shuffle() {
for (int i = 1; i <= 20; i++)
{
int a = (int)(Math.random() * 12);
int b = (int)(Math.random() * (52 - 12));
swap(a,b);
}
}
private void swap(int a,int b){
Card temp = deck[a];
deck[a] = deck[b];
deck[b] = temp;
}
private void print() {
...
}
}
在你的主要方法中做類似的事情
Deck d = new Deck();
deck.shuffle();
deck.print();

TA貢獻(xiàn)1860條經(jīng)驗(yàn) 獲得超9個(gè)贊
在java中,該方法無法按您的預(yù)期工作(https://www.google.com/?q=java+call+by+value ... https://stackoverflow.com/a/40523/592355),但你可以解決:
您可以將輸出變量封裝在一個(gè)對象內(nèi)(該修改將在方法退出后持續(xù)存在):
和
class TwoInts {
int a,b;
}
和:
private static void randomInt(TwoInts container) {
assert(conatiner != null);
container.a = (Math.random() * 12);
container.b = (Math.random() * 12);
}
最直接的方法是(編寫一個(gè)具有一個(gè)返回值的方法):
private static int rand(int offset, int max) {
return (int) (Math.random() * max) + offset;
}
..并調(diào)用它兩次:
a = rand(0, 12);
b = rand(0, 12);
...
還請您看一下java.util.Random...

TA貢獻(xiàn)1906條經(jīng)驗(yàn) 獲得超3個(gè)贊
如果您希望應(yīng)用程序從 randomInt 方法返回兩個(gè)值 a 和 b,則不能僅將 a 和 b 聲明為參數(shù)。java中的方法參數(shù)是“ByValue”參數(shù)。該方法不會(huì)更改調(diào)用者的 a 和 b 值。
首選選項(xiàng):
讓 randomInt 返回一個(gè)包含兩個(gè)元素的數(shù)組。調(diào)用 randomInt 后,您可以將數(shù)組中的值分配給調(diào)用方方法中的變量 a 和 b。
替代選項(xiàng),通過數(shù)組進(jìn)行偽引用:
不要傳遞 a 和 b,而是將一個(gè)只有一個(gè)元素的數(shù)組傳遞給您的方法:
private static void randomInt(int[] a, int[] b)
{
//assuming a[] and b[] both are an array with just one element
//set a[0] and b[0] here like you already set a and b
}
在呼叫方,
...
int[] a = new int[1];
int[] b = new int[1];
randomInt(a, b);
//now you have your values in a[0] and b[0].

TA貢獻(xiàn)1817條經(jīng)驗(yàn) 獲得超14個(gè)贊
您可以將 a 和 b 變量聲明為全局變量
int a,b;
private static void shuffle(Card [] cardArray)
{
for (int i = 1; i <= 20; s++)
{
randomint();
Card temp = cardArray[a];
cardArray[a] = a;
cardArray[b] = b;
}
}
private static void randomInt()
{
a = (Math.random() * 12);
b = (Math.random() * 12);
}
添加回答
舉報(bào)