자바(JAVA)
[자바(Java)] 임의의 정수 만들기(난수)
Hana_h
2022. 10. 25. 21:44
// 난수 생성기
- 임의의 수를 만들어내는 도구
- 랜덤값
1. Math.random()
- 0.0 <= Math.random() <1.0
- 0.0 <= Math.random() * 10 < 10.0
- 0 <= (int)(Math.random() * 10) < 10
- 1 <= (int)(Math.random() * 10) + 1 < 11
- 3 <= (int)(Math.random() * 5) + 3 < 8
2. Random 클래스
- Math.random
public class Ex4_7 {
public static void main(String[] args) {
int num = 0;
for (int i = 1; i <= 20; i++) {
//System.out.println(Math.random()*10);
//System.out.println((int)(Math.random()*10));// 0 <=x<10
System.out.println((int)(Math.random()*10) +1);// 1<=x<=10
}
}
}
package com.test.java;
public class Ex31_for {
public static void main(String[] args) {
m19();
} //main
private static void m19() {
//난수 생성기
//1. Math.random()
System.out.println(Math.random());
System.out.println(Math.random() * 10);
System.out.println((int)(Math.random() * 10));
System.out.println((int)(Math.random() * 10) + 1);
System.out.println();
// 3~7 > 0~4 구한 후 +3
System.out.println((int)(Math.random() * 5) + 3);
}