【问题标题】:How can I display an array from a void method?如何从 void 方法显示数组?
【发布时间】: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 设置为随机值?
  • 当你传递一个数组时,你传递的是对它的引用。一旦离开该方法,该方法中数组内部的任何更改都会存在。

标签: java arrays void


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    您的代码中有很多问题。

    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();
    

    【讨论】:

      【解决方案3】:

      为什么它不工作的解释:

      您要执行的操作:将 dice(您传入的参数)更改为等于 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);
      }
      

      【讨论】:

        猜你喜欢
        • 2023-04-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多