본문 바로가기

이것저것 배운것/JAVA 공부중

난수를 발생시키는 2가지 방법.

자바에서 난수를 발생시키는 방법으로는 2가지 방법이 있다.


첫번째는 Math클래스의 random메서드를 이용하여 난수를 발생시키는 방법이다.


아래의 예제로 설명하자면, 0~1 사이의 double형 난수를 리턴한 후 * 10을 하고,

그 값을 int형으로 a,b,c,d,e에 반환하여 출력하는 것이다.

public class HelloWorld{

     public static void main(String []args){
        int a = (int) (Math.random()*10);
        int b = (int) (Math.random()*10);
        int c = (int) (Math.random()*10);
        int d = (int) (Math.random()*10);
        int e = (int) (Math.random()*10);
        System.out.println(a+","+b+","+c+","+d+","+e);
     }
}

<결과>


두번째는 Random 클래스를 사용하는 방법이다.

Boolean nextBoolean()

float nextFloat() 등등


random.nextInt(100)을 입력하면, 0~100사이의 난수가 발생한다.

import java.util.Random;

public class HelloWorld{

     public static void main(String []args){
         Random random = new Random();
         int f = random.nextInt(10);
         int g = random.nextInt(10);
         int h = random.nextInt(10);
         int i = random.nextInt(10);
         int j = random.nextInt(10);
         System.out.println(f+","+g+","+h+","+i+","+j);
     }
}

<결과>