📗 Docs

[Java] 자바 난수(랜덤 숫자) 생성하기 (Math, Random)

파일과 미디어
date
Apr 20, 2023
slug
Java-Random
author
status
Public
tags
Java
Blog
summary
type
Post
thumbnail
category
📗 Docs
updatedAt
Apr 24, 2023 06:33 PM
자바에서 난수를 얻어내는 방법은 Random클래스를 활용하는 방법과 Math클래스를 활용하는 방법 2가지가 있다.
두 방벙의 차이점은 Math.random() 메소드는 0.0에서 1사의 double 난수를 얻는데만 사용한다면, Random 클래스는 boolean, int, long, float, double 난수를 얻을 수 있다.

Math.random()

public class RandomExample {
    public static void main(String[] args)  {
        System.out.println("0.0 ~ 1.0 사이의 난수 1개 발생 : " + Math.random());
        System.out.println("0 ~ 10 사이의 난수 1개 발생 : " + (int)((Math.random()*10000)%10));
        System.out.println("0 ~ 100 사이의 난수 1개 발생 : " + (int)(Math.random()*100));
    }
}
 
  • Math 클래스는 최상위 클래스인 Object 클래스 안에 있으므로 따로 Import를 시켜주지 않아도 사용이 가능하며 Math.random()메소드도 static메소드로 이루어져있기 때문에 바로 호출 가능하다.
  • Math.random() 메서드를 실행하면 실수형의 0.0 ~ 1.0 미만 사이의 무작위 실수값이 하나 리턴도니다. 소수점 자리수가 무한한 무한소수의 형태로 출력되므로 무한에 가까운 경우의 수가 나타난다.
 

Math.random()을 정수로 사용하기

  1. random의 값을 충분히 높여준뒤 나머지 연산을 한다.
  1. random의 값을 원하는 자리수만큼 곱한 뒤 int형으로 변환되면 소수점 단위는 자동으로 절삭된다.

Random 클래스 활용

improt java.util.Random;

public class RandomExample {
	public static void main(String[] args)  {
        Random random = new Random(); //랜덤 객체 생성(디폴트 시드값 : 현재시간)
        random.setSeed(System.currentTimeMillis()); //시드값 설정을 따로 할수도 있음

        System.out.println("n 미만의 랜덤 정수 리턴 : " + random.nextInt(10)); 
        System.out.println("무작위 boolean 값 : " + random.nextBoolean());
        System.out.println("무작위 long 값 : " + random.nextLong());
        System.out.println("무작위 float 값 : " + random.nextFloat());
        System.out.println("무작위 double 값 : " + random.nextDouble());
        System.out.println("무작위 정규 분포의 난수 값 :" + random.nextGaussian());
    }
}
 
Random 클래스는 java.utill 패키지안에서 있어 사용시 import가 필요하고 new를 통해 객체를 생성해주어야 합니다. 기본 생성자를 통해 Random객체를 생성하면 현재시간을 종자값으로 사용하고 setSeed메서드를 통해 시드값을 따로 설정해줄수도 있다.
 

로또 번호 생성

import java.util.Random;

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

        Random rd = new Random();//랜덤 객체 생성
    
        for(int i=0;i<6;i++) {
            System.out.print((rd.nextInt(45)+1) + " "); //로또번호 출력
        }
    }
}