double d = Math.random();
random metodu static olduğundan dolayı, kullanmak için bir nesne oluşturulmasına gerek yoktur.
Üretilen değeri ekrana yazdırmak için aşağıdaki satırı projemize ekleyelim.
System.out.println(d);
Math sınıfının random metodunu kullanarak bir tam sayı üretmek istersek, işin içerisine biraz matematik katmamız yeterli olacaktır.
int i = (int)(Math.random()*10);
System.out.println(i);
random metodundan dönen değer 0 ile 1 arasında ve double türünde olduğundan dolayı, bu değeri 10 ile çarpıp elde edilen yeni değeri int tipine cast ederek, küsüratın kesilip atılmasını sağlarız ve tamsayı hanesini elde ederiz.
Kodların son hali ve çalıştırıldığında elde edilecek olan örnek çıktı aşağıdaki görselde sunulmuştur.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MathRandom | |
{ | |
public static void main(String[] args) | |
{ | |
double d = Math.random(); | |
System.out.println(d); | |
int i = (int)(Math.random()*10); | |
System.out.println(i); | |
} | |
} | |
// http://ercanbozkurt.blogspot.com.tr/2014/04/java-math-sinifinin-random-metodu-ile.html |
Hiç yorum yok:
Yorum Gönder