簡體   English   中英

Java以不同的方法獲取不同的隨機數

[英]Java Getting different random numbers in different methods

所以我正在用Java開發這個yahtzee游戲,我想用這些骰子顯示1-6。 我的問題是,我用不同的方法得到了不同的“骰子數”。

我的隨機骰子方法:

public String roll(){
    int dice1 = (int )(Math.random() * 6 + 1),
            dice2 = (int )(Math.random() * 6 + 1),
            dice3 = (int )(Math.random() * 6 + 1),
            dice4 = (int )(Math.random() * 6 + 1),
            dice5 = (int )(Math.random() * 6 + 1);

    return dice1 +"   "+ dice2 +"   "+ dice3 +"   "+ dice4  +"   "+ dice5;
}

因此,我有另一個動作偵聽器方法。 我有一個用於擲骰子的按鈕。 在此方法內部,我想擁有它,以便在按下按鈕時生成這些隨機數,以便可以在paintComponent方法中使用它們。 但是,當我嘗試執行此操作時,我的actionListener方法和繪畫組件中得到的數字不同。

這是我的動作監聽器:

roll.addActionListener(
            new ActionListener(){
        public void actionPerformed(ActionEvent event){


            if(turn == true){

                roll();

                rolls++;
                start = false;
                updateUI();
                System.out.println( roll() );

            }
            if(rolls == 3){
                turn = false;
                System.out.println("Out of rolls");
            }

        }
    });

和我的paintComponent:

public void paintComponent(java.awt.Graphics g){
    super.paintComponent(g);
    this.setBackground(Color.BLUE);



    g.setColor(Color.WHITE);
    g.fillRoundRect(getWidth() / 2 - 25, getHeight() / 2 - 35, 12, 12, 0, 0);   //Dice 1
    g.fillRoundRect(getWidth() / 2 - 10, getHeight() / 2 - 35, 12, 12, 0, 0);   //Dice 2
    g.fillRoundRect(getWidth() / 2 + 5, getHeight() / 2 - 35, 12, 12, 0, 0);    //Dice 3
    g.fillRoundRect(getWidth() / 2 + 20, getHeight() / 2 - 35, 12, 12, 0, 0);    //Dice 4
    g.fillRoundRect(getWidth() / 2 + 35, getHeight() / 2 - 35, 12, 12, 0, 0);    //Dice 5



    if(start == false){
        g.setColor(Color.BLACK);
        g.drawString( roll() , getWidth() / 2 - 25 , getHeight() / 2 - 25 );
    }


}

我基本上想在所有方法的骰子上使用相同的數字,直到我再次按下roll來更新它們。

g.drawString( roll() , getWidth() / 2 - 25 , getHeight() / 2 - 25 );

此方法中的調用是一個額外的調用,您將重新計算數字,因為再次調用了Math.random(),因此,如果您要重新繪制jPanel,也只需調用該方法

問題在於,每次調用roll()時,您都在生成新的隨機數,因此它將以不同的方式返回。 您需要在第一次調用roll()時將結果存儲在某個地方,並且僅在希望更改骰子時才再次調用它。

請嘗試以下更改。

在類聲明中:

private String rollResult = "";

在actionPerformed(...)中:

public void actionPerformed(ActionEvent event){


        if(turn == true){

            rollResult = roll();

            rolls++;
            start = false;
            updateUI();
            System.out.println( rollResult );

        }

在paintComponent(...)中:

if(start == false){
        g.setColor(Color.BLACK);
        g.drawString( rollResult , getWidth() / 2 - 25 , getHeight() / 2 - 25 );
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM