2016-12-19 40 views
1
public class numberCube { 

    public static int size; 
    public static int tosses; 
    public static int random; 
    public static int value; 
    public static int values; 


    public static void cubeSize(){ 

//獲取允許被隨機需要幫助基於用戶輸入的數字隨機

String x = JOptionPane.showInputDialog 
       ("How many numbers do you want on your cube?"); 

     int size = Integer.parseInt(x); 

    } 
    public static void numTosses(){ 

號碼的範圍//獲取的倍量是一個隨機將循環

String y = JOptionPane.showInputDialog 
       ("How many times do you want to toss the dice?"); 

     int tosses = Integer.parseInt(y); 

    } 

    public static void randomizer(){ 

//創建隨機數。下面是問題所在。我需要//能夠讓用戶指定數字的範圍以及它將被隨機化的次數 例如,對於cubeSize(),我可以輸入3,對於numTosses(),我可以輸入5。可能的輸出爲:1,1,3,2,3

} 

} 
} 
+0

呃..是什麼問題?我想知道什麼'int value = 16 + random.nextInt(5);'做的,你期望它做什麼..據我所知它會導致'16 +從0到4的一些隨機數。所以,它會給出16到20左右的數字。 –

+0

我的不好,那代碼是從谷歌某處複製的。整個randomizer()方法可以改變,但最好的辦法是,因爲我不知道從哪裏開始。 – Jonathan

回答

0

您在此處複製變量(ex: size,tosses,etc)的初始化。

如果想操縱特定類的屬性,您需要使用this關鍵字。所以,

int size = Integer.parseInt(x);成爲this.size = Integer.parseInt(x);

int tosses = Integer.parseInt(y);randomizer()方法變得this.tosses = Integer.parseInt(y);

etc..

那麼你可以嘗試這樣的:

Random random = new Random(); 
for (int i = 1; i <= this.tosses; i++) { 
    int value = 1 + random.nextInt(this.size); 
    System.out.println(value); 
} 
+0

非常感謝!完美工作。 – Jonathan

+0

np!如果有幫助,不要忘記接受它,因爲它可能對未來的其他人有用!快樂編碼... –

0

你的意思是這樣的嗎?

Random r = new Random(); 
for (int i = 0; i < numTosses; ++i) { 
    int rand = 1 + r.nextInt(cubeSize); 
    // use rand, which will be an integer from 1 to cubeSize (inclusive) 
} 
+0

是的,這正是我想要的,但是當我使用變量而不是實際數字時,它似乎不會輸出任何內容。 – Jonathan