본문 바로가기
Language/Java

[Java] 난수 (Random Number) 생성하기

by jungwon3004 2022. 1. 14.
728x90
반응형

Java에서 난수를 생성하는 아주 간단한 방법에 대해 이야기해보자.

728x90

1. Math.random()

가장 쉬운 방법이다.

double d = Math.random();

따로 뭔가 import할 필요도 없이 그냥 이거면 된다.

 

하지만 그만큼 한계는 분명하다.

따로 범위 지정은 안 되고 0.0이상 1.0미만의 double 값을 random으로 return한다.

 

머리를 조금 쓰면 int나 char 타입이 어느정도는 가능할 것 같다는 게 느껴진다.

double d = (int)*(Math.random()*10);

이렇게하면 0이상 9이하의 정수가 나올 수 있을 것이다.

int i = (int)*(Math.random()*100);

이렇게 하면 0이상 99이하일 것이다.

하지만 이건 한계가 있다.

0~79 이런 식의 디테일한 조건을 설정하려면 코드가 너무 지저분해진다.

 

또한 char type을 만들려면 ascii code번호 계산해서 가능은 할 것이다.

char alphB = (char)((Math.random()26)+65); //대문자
char alphB = (char)((Math.random()26)+97); //소문자

 

하지만 이보다 더 디테일하게 가능한 방법이 있다.

범위 지정이 필요한 경우라면 2번 방법을 사용하자

 

반응형

2. Random class를 활용하기

java.util package에 Random이라는 class가 있다.

import java.util.Random;

public class Test{
	public static void main(String[] args){
    	Random rand = new Random();
		int ranNum=rand.nextInt(101);
    }
}

이렇게 사용하면 된다.

import한 뒤, Random의 instance를 만들고, 그 instance의 method를 사용하면 된다.

위에서는 .nextInt()를 사용했는데 사실 그 종류는 다양하다.

 

boolean nextBoolean()

int nextInt()

int nextInt(int n) : 0이상 n미만 int

double nextDouble() : 0.0이상 1.0미만 double

float nextFloat() : 0.0이상 1.0미만 float

long nextLong()double nextGaussian() : 정규분포의 난수 (평균0, 표준편자1)

 

 

3. 예제

간단한 예로,

난수 50개를 출력하라

 (조건1) 0~100 사이의 정수

 (조건2) 1줄에 6개씩 표기하라

 (조건3) 마지막 줄에는 50개의 합을 출력하라

import java.util.Random;

public class Test{
	public static void main(String[] args){
    	ran();
    }
    public static void ran() {
		Random rand = new Random();
		
		int sum=0;
		int now=0;
		int ranNum;
		for(int i=0; i<50; i++) {
			ranNum=rand.nextInt(101);
			sum+=ranNum;
			now+=1;
			System.out.printf("%-5d",ranNum);
			if(now==6) {
				System.out.println("");
				now = 0;
			}
		}
		System.out.println();
		System.out.println(sum);
	}
}

사실 이래저래 적었지만, 굉

728x90
반응형