-
[JAVA 37] 자바 랜덤 / 무작위 ( Random )Language/Java 2018. 2. 26. 15:45반응형
■ Random ( 랜덤 )
1. With Random
12345678910111213141516171819import java.util.*;class RandomS2{Random random = new Random();void m1(){ // 방법 1. With Randomint a = 3;int b = random.nextInt(a); // 0 , 1 , 2 >> 0 ~ ( n-1 )System.out.println("b : " + b);boolean c = random.nextBoolean();System.out.println("c : " + c);}public static void main(String[] args){RandomS2 rs2 = new RandomS2();rs2.m1();}}cs 2. With Math
12345678910111213141516import java.util.*;class RandomS2{Random random = new Random();void m1(){ // 방법 2. With Mathint a = 3;int b = Math.random();System.out.println("b : " + b);}public static void main(String[] args){RandomS2 rs2 = new RandomS2();rs2.m1();}}cs error : incompatioble type : possible lossy conversion from fouble to int
에러 : 호환되지 않는 타입 : double 에서 int 로 변형시에 정보손실 가능성이 있다.
int b = Math.random();
1234567891011121314151617import java.util.*;class RandomS2{Random random = new Random();void m1(){ // 방법 2. With Mathint a = 3;double b = Math.random(); // 0 < 값 < 1int c = (int)(a*b); // 0 , 1 , 2System.out.println("c : " + c);}public static void main(String[] args){RandomS2 rs2 = new RandomS2();rs2.m1();}}cs 3. 기본
1234567891011121314import java.util.*;class RandomS1{ // Random Study 1Random random = new Random();void showRandom(){int i = random.nextInt(7); // 0 ~ (n-1) >> 0 ~ 6 >> 7개System.out.println("i : " + i);}public static void main(String[] args){new RandomS1().showRandom();}}cs 0 ~ 6 까지 random.nextInt(7);
0 , 1 , 2 , 3 , 4 , 5 , 6
즉 7개 중에 하나
2. 응용
123456789101112131415161718192021222324import java.util.*;class RandomS1{ // Random Study 1Random random = new Random();void showRandom(){int i = random.nextInt(7); // 0 ~ (n-1) >> 0 ~ 6 >> 7개System.out.println("i : " + i);switch(i){case 0 : System.out.print("일"); break;case 1 : System.out.print("월"); break;case 2 : System.out.print("화"); break;case 3 : System.out.print("수"); break;case 4 : System.out.print("목"); break;case 5 : System.out.print("금"); break;case 6 : System.out.print("토");}System.out.println("요일");}public static void main(String[] args){new RandomS1().showRandom();}}cs 반응형'Language > Java' 카테고리의 다른 글
[JAVA/자바] 가위 바위 보 게임 예제 (0) 2018.02.26 [JAVA 38] 자바 주석 ( Coment ) (0) 2018.02.26 [JAVA/자바] 학점계산기 예제 (0) 2018.02.24 [JAVA 36] 자바 입출력 ( IO ( Input / Output )) (4) 2018.02.23 [JAVA 35] 자바 쓰레드 ( Thread ) (0) 2018.02.20