簡體   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