어제 오늘 내일

[Java] 4자리 수 난수 생성하기 본문

IT/Java

[Java] 4자리 수 난수 생성하기

hi.anna 2025. 3. 19. 06:34

Java에서 4자리 난수 생성하기

Java에서 4자리 숫자로 된 난수(1000 ~ 9999) 를 생성하는 여러 가지 방법을 살펴보겠습니다.

 

1. Random 클래스를 이용한 4자리 난수 생성 (간단한 방법)

import java.util.Random;
public class FourDigitRandom {
public static void main(String[] args) {
Random random = new Random();
int randomNumber = 1000 + random.nextInt(9000); // 1000 ~ 9999
System.out.println("4자리 난수: " + randomNumber);
}
}

출력

4자리 난수: 3748

 

 

2. Math.random()을 이용한 4자리 난수 생성

public class MathRandomExample {
public static void main(String[] args) {
int randomNumber = (int)(Math.random() * 9000) + 1000; // 1000 ~ 9999
System.out.println("4자리 난수: " + randomNumber);
}
}

출력

4자리 난수: 5723
  • Math.random()은 0.0 이상 1.0 미만의 실수를 반환.
  • (Math.random() * 9000) + 1000 → 1000~9999 범위의 정수값 생성.

 

3. SecureRandom을 이용한 보안성이 높은 4자리 난수 생성

import java.security.SecureRandom;
public class SecureRandomExample {
public static void main(String[] args) {
SecureRandom secureRandom = new SecureRandom();
int randomNumber = 1000 + secureRandom.nextInt(9000); // 1000 ~ 9999
System.out.println("보안 난수: " + randomNumber);
}
}

출력

보안 난수: 8256

 

  • SecureRandom은 예측이 어려운 난수를 생성하므로 보안 관련된 작업에 적합.
  • 금융, 보안 인증 코드 생성 시 유용.

 

4. UUID를 이용한 4자리 난수 생성

import java.util.UUID;
public class UUIDExample {
public static void main(String[] args) {
String uuid = UUID.randomUUID().toString().replaceAll("[^0-9]", ""); // 숫자만 남기기
String randomFourDigits = uuid.substring(0, 4); // 앞의 4자리 가져오기
System.out.println("UUID 기반 난수: " + randomFourDigits);
}
}

출력

UUID 기반 난수: 8372

 

  • UUID.randomUUID()를 생성한 후 숫자만 추출하여 4자리만 사용.
  • 고유성이 높아 중복 발생 가능성이 적음.

 

5. String.format()을 활용한 4자리 난수 생성 (0으로 시작 가능)

import java.util.Random;
public class FormatRandomExample {
public static void main(String[] args) {
Random random = new Random();
String randomNumber = String.format("%04d", random.nextInt(10000)); // 0000 ~ 9999
System.out.println("4자리 난수 (0 포함 가능): " + randomNumber);
}
}

출력

4자리 난수 (0 포함 가능): 0348

 

  • String.format("%04d", random.nextInt(10000))
    • 10000 이하의 난수를 생성하고 4자리로 맞추기 위해 앞에 0을 추가.
    • 0001, 0456, 9999 등 0으로 시작하는 숫자 포함 가능.

 

6. 성능 및 보안 비교

방법 보안성 중복 가능성 속도 사용예
Random.nextInt(9000) + 1000 낮음 중복 가능 빠름 일반적인 난수 생성
Math.random() 낮음 중복 가능 빠름 간단한 난수 생성
SecureRandom.nextInt(9000) + 1000 높음 중복 가능 느림 OTP, 인증 코드, 보안 관련
UUID 기반 4자리 숫자 높음 중복 가능성 거의 없음 느림 유니크한 난수 필요할 때
String.format("%04d", random.nextInt(10000)) 낮음 중복 가능 빠름 0 포함 4자리 숫자 필요 시

 

7. 정리

일반적인 4자리 난수 Random.nextInt(9000) + 1000
0으로 시작하는 4자리 숫자 String.format("%04d", random.nextInt(10000))
보안이 필요한 경우 SecureRandom.nextInt(9000) + 1000
고유한 난수가 필요한 경우 UUID 기반 숫자

 

 

반응형
Comments