프로그래밍

[자바 기초] day03 : 난수 생성하기(Random 클래스 활용) 본문

자바/자바 기초

[자바 기초] day03 : 난수 생성하기(Random 클래스 활용)

시케 2023. 5. 6. 16:42
728x90
반응형

2023.05.04.목

난수 생성하기

자바에서 난수를 생성하는 방식 중 Random 클래스를 활용하는 방법을 알아보자

Random 클래스는 java,util 패키지안에 있어 import 가 필요하다

import java.util.Random;

public class RandomEx {
	public static void main(String[] args)  {
        Random random = new Random(); //랜덤 객체 생성
        
        int N = rand.nextInt(10);			//1~10 랜덤 수 생성

        System.out.println("n 미만의 랜덤 정수 리턴 : " + N); 
    }
}

 

rand 연산 사용

int N = rand.nextInt(개수)+최소값;

 

 

Random클래스 주요 메서드

메서드 설명
setSeed(long n) 매개값으로 주어진 종자값이 설정됩니다.
boolean nextBoolean() boolean타입의 난수를 리턴합니다.
double nextDouble() double 타입의 난수를 리턴합니다.
int nextInt()  int 타입의 난수를 리턴합니다.
int nextInt(int n) int 타입의 0 ~ 매개값까지의 난수를 리턴합니다.
double nextGaussian() 평균이 0.0이고 표준편차가 1.0인 정규분포 난수를 리턴합니다.

 

n개의 랜덤정수 생성하기

import java.util.Random;

public class Test02 {
	public static void main(String[] args) {
		Random rand = new Random();			//랜덤 연산자
		int N = rand.nextInt(101);			//0~100
		
		int[] data = new int[N];			//데이터 담을 배열 선언

		int index = 0;	//현재위치를 나타내는 변수

		for(int i =0; i<data.length; i++) {
			data[i]=rand.nextInt(6)+100;	//100~105 랜덤 수 생성
			}
	}
}

 

flag 알고리즘

 : 특정상황이 T/F인지 판단
특정상황이 반복문 함수 등처럼
시간이 좀 흘러야 범위를 모두 확인해야 알 수 있을 때

 

단순 입력값일땐 사용하지 않는다

주로 배열에 있는지

 

 

중복되지 않은 랜덤정수

import java.util.Random;

public class Test04 {

	public static void main(String[] args) {

		int[] data=new int[3];
		
		Random rand=new Random();
		int index=0; // 배열 내에서 현재위치
		
		while(true) {
			
			if(index==data.length) {
				break;		//배열이 완성
			}

			data[index]=rand.nextInt(10)+1;	//1~10
			boolean flag=false;
			

			for(int i=0;i<index;i++) {		//비교해야 할 횟수
				if(data[index]==data[i]) { // 특별한 일 : 중복발생
					flag=true;
				}
			}

			if(flag==true) {
				continue;
			}
			

			index++;
		}

		for(int v:data) {
			System.out.println(v);
		}


	}

}

 

다음 순서도를 참고하면 이해가 쉽다

 

flag는 중복 여부이다

중복이라면 flag를 true, 중복이 아니라면 flag를 false 로 변경한다

flag가 true라면 index가 증가되지 않고 다시 한번 난수를 생성한다

flag가 false라면 index가 증가되고 다음으로 넘어간다

 

 

 

깃허브

https://github.com/jihyean/Java/tree/main/day03/src

 

GitHub - jihyean/Java

Contribute to jihyean/Java development by creating an account on GitHub.

github.com

 

728x90
반응형
Comments