【发布时间】:2015-04-16 20:27:30
【问题描述】:
我是 java 的初学者,我正在尝试制作 Yahtzee 游戏,并且需要从 void 方法中随机掷骰子作为数组。有人可以向我解释为什么这行不通吗?
import java.util.Arrays;
public class YatzeeGame {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] diceRolls = new int[5];
diceRolls = throwDice(diceRolls);
System.out.println(display(diceRolls));
}
public static void throwDice(int [] dice) {
int [] roll = {(int)(Math.random()*6+1),
(int)(Math.random()*6+1),(int)(Math.random()*6+1),
(int)(Math.random()*6+1),(int)(Math.random()*6+1),
(int)(Math.random()*6+1)};
dice = roll;
}
public static String display(int [] dice) {
String str = Arrays.toString(dice);
str = str.replace("[", "");
str = str.replace("]", "");
str = str.replace("," , " ");
return str;
}
【问题讨论】:
-
Void 的定义是“不返回任何东西”。您确定必须从 void 方法中掷骰子吗?
-
好吧,我的指令指出“throwDice(int [] dice) 方法接受一个整数数组并将该数组的值设置为 5 个随机骰子面值。它什么也不返回。”如何使用它来将 diceRolls 设置为随机值?
-
当你传递一个数组时,你传递的是对它的引用。一旦离开该方法,该方法中数组内部的任何更改都会存在。