티스토리 뷰

java.lang.Math의 random() 사용하기 : Math.random()

  • min부터 ~ max까지 출력하고 싶다!

    • Math.random() * (max - min + 1) + min

  • 시작값부터 x개를 출력하고 싶다!

    • Math.random() * x + 시작값

 

 

java.util.Random 사용하기 : Random r = new Random();

  • 0부터 ~ num-1까지 출력하고 싶다!

    • nextInt() 에 값을 넣어줍니다.

  • 시작값부터 x개를 출력하고 싶다!

    • r.nextInt(x) + 시작값

 

 

package com.test02;

import java.util.Random;

public class MTest {

	public static void main(String[] args) {

		random01();
		random02();		
		random03();
	}


	// java.lang.Math 사용하기	
	public static void random01() {

		// 0.0 <= Math.random() < 1.0
		double d = Math.random();
		System.out.println(d);
	}
	
	public static void random02() {

		int max = 10;
		int min = 5;
		int r1 = (int) (Math.random() * (max - min + 1)) + min; // 5 ~ 10
		int r2 = (int) (Math.random() * 5 + 1); // 1 ~ 5
		
		System.out.println(r1);
		System.out.println(r2);
	}
	
	
	// java.util.Random 사용하기
	public static void random03() {
		
		Random r = new Random();
		
		System.out.println(r.nextInt(10)); // 0 ~ 9
		System.out.println(r.nextInt(6) + 5); // 5 ~ 10
	}
}

출력 결과

최근에 올라온 글
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Total
Today
Yesterday