2017-08-30 115 views
0

在java中顯示隨機數的特定範圍所以,我對編程相當陌生,並開始學習Math.random。我試圖編寫一個程序,將打印4-12之間的值,但我似乎無法只打印該範圍內的值。它打印13,我不想如何使用Math.random

我的代碼:

public class MathRandom{ 
    public static void main(String[] args){ 

     for(int x = 0; x < 10; x++){ //Just to test what numbers are displayed 
     System.out.println((int) (Math.random() * 10) + 4); 

     } 
    } 
} 

我錯過了什麼?在此先感謝您的幫助

+0

創建一個所需元素(4 - 12)的數組,然後從中選擇隨機索引。 Int [] ArrayVariable = [4,5,...,12]; random =從0到ArrayVariable中元素的數量 system.out.println(ArrayVariable [random]); – Nubian

+0

谷歌是你的朋友:*** 4.710.000結果(0,59秒)*** –

+0

兄弟,你必須是盲人。我問如何在任何兩個值之間生成任意的隨機數。不是陣列!完全不同 – 5ilv3r

回答

0

更改行這樣的: -

System.out.println((int) (Math.random() * 9) + 4); 

這將從0-8產生一個隨機數,然後添加4到它,這意味着其結果將是,由4- 12。

+0

我可以問一下,但是爲什麼它是9而不是10?你能解釋一下,以便我能理解它的工作原理嗎? – 5ilv3r

+0

4,5,6,7,8,9,10,11,12 <--- 9個不同的值 – CSmith

+0

'Math.random()* 9'產生數字0-8(即小於9的數字)。 'Math.random()* 10'生成數字0-9。 https://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#random()請注意,雖然有更好的方法來獲得隨機數字。 –