繁体   English   中英

如何通过void方法显示数组?

[英]How can I display an array from a void method?

我是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;
}

他们希望您替换阵列,如果您只分配它就不会发生。 注意,返回数组仍然被认为是更好的方法。 额外的技巧:在您现有的代码中,您制作一个数组,大小为5,另一个数组大小为6。由于您将其命名为zahtzee,我们将使用5。

public static void throwDice(int [] dice) {     
    for (int x = 0; x < 5; x++)
        dice[x] = (int)(Math.random()*6+1);
}

解释为什么它不起作用:

您要执行的操作:将骰子(您传入的参数)更改为等于roll。 本质上,(如果我在这里没有记错的话)您正在尝试使用throwDice更改diceRolls。

您实际上在做什么:您已经传递了diceRolls并说“在这里,我们称它为骰子”。 然后,在函数结束时,您实际上已经说过“骰子不再意味着diceRolls。骰子现在意味着滚动”。 这意味着diceRolls仍然没有改变。

您需要更改dice的实际值,而不是更改骰子是什么。 例如:

public static void throwDice(int[] dice) {
    // change the actual values of dice, instead of changing dice
    dice[0] = (int) (Math.random() * 6 + 1);
    dice[1] = (int) (Math.random() * 6 + 1);
    dice[2] = (int) (Math.random() * 6 + 1);
    dice[3] = (int) (Math.random() * 6 + 1);
    dice[4] = (int) (Math.random() * 6 + 1);
}

您的代码中有很多错误。

throwDice方法中, dice是一个局部变量,因此将其更改为roll ,后者是另一个局部变量,不会影响该方法之外的任何内容。

同样,您的返回类型为void ,因此无法使用该方法设置任何变量。

您可能有一个返回int[]

public static int[] throwDice() {
    int[] roll = new int[6];
    for (int i = 0; i < 6; i++) {
        roll[i] = (int) (Math.random() * 6) + 1;
    }
    return roll;
}

然后像这样使用它:

int[] diceRolls = throwDice();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM