[JAVA]

10. 조건문/반복문_2

혜리노베이션 2023. 5. 11. 21:24

// 조건문/반복문_2

/*
1. 임의 정수 만들기 - Math.random
-

Math.random() - 0.0 ~ 1.0 사이에 임의의 double값을 반환
  0.0 <= Math.random() < 1.0, 즉 0.0~0.9999...
 예) 1~3의 범위를 설정하고 싶다면?
    (1) 각 변에 3을 곱한다
        0.0 * 3 <= Math.random() * 3 < 1.0 * 3
        0.0 <= Math.random() * 3 < 3.0  ==> 0.0 ~ 2.99999...
    (2) 각 변을 int형으로 변환한다.
        (int)0.0 <= (int)(Math.random() * 3) < (int)3.0 ==> 0 ~ 2
    (3) 각 변에 1을 더한다
        0 + 1 <= (int)(Math.random() * 3 ) + 1 < 3 + 1 ==> 1 ~~ 3

2. for문


- 조건을 만족하는 동안 블럭 {}을 반복 - 반복횟수를 알 때 적합 * 모를 떈 while이 적합
  for(int i=1; i<=5; i++) { ==> 1부터 5까지 1씩 증가
    sout("I can do it."); // 5번 반복
    }
    조건식이 거짓일 때 까지 반복
* 범위를 좁히는 게 좋음
 */


public class JAVA10_random_for_while {
    public static void main(String[] args){
        // Q1. 1~10사이 난수를 20개 출력
        for(int i = 1; i <= 20; i++) {
//            System.out.println((int)(Math.random()*10)); // 원하는 범위를 곱함 => 범위: 0~9
              System.out.println((int)(Math.random()*10)+1); // 1~10
        }

        for(int i=1; i <= 10; i=i*2) { // i=1, 2, 4, 8, 16 ==> 16은 false
            System.out.println("Hello"); // {}안에 문장을 4번 반복
        }
    }
}