# 랜덤 관련 클래스
* java.util.Random
  - nextInt(int n) : 0부터 지정된 n의 범위(n은 포함하지 않음)sodml int형 난수를 리턴한다.
* java.lang.Math
  - random() : 0.0 이상으로 1.0보다 작은 양의 부호가 붙은 double형 난수를 리턴한다.
                    그리고 이 메소드는 java.util.Random클래스의 nextDouble() 메소드를 호출하도록되어 있다.

# 응용
1. 사이트 운영시 유저가 패스워들

잊어버렸을 경우 임시로 패스워드를 발급해줘야 하는 경우가 발생한다.
   이때 아래 소스를 이용하면 쉽게 생성이 가능하다.

import java.util.Random;


public class RandomSample{

    static Random rnd = new Random();
    
    public static void main(String[] args) {     	    
    	final char[] possibleCharacters = {'0','1','2','3','A','B','C','%'};
        final int possibleCharacterLength = possibleCharacters.length;
        final int passwordSize = 10;
        StringBuffer passwordBuf = new StringBuffer(passwordSize);
        
        for(int i=0; i<passwordSize; i++){
        	passwordBuf.append(possibleCharacters[rnd.nextInt(possibleCharacterLength)]);
        }
        System.out.println(passwordBuf.toString());
    }
}


possibleCharacters 는 임시 패스워드를 생성할 때 사용할 문자들이고, passwordSize 임시 패스워드의 길이를
의미한다.
rdn.nextInt()를 이용하여 0부터 possibleCharacterLength까지의 난수를 발생시킨다음 possibleCharacters 배열에서 해당 문자를 추출하여 StringBuffer에 저장한다.

반응형
  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기