본문 바로가기
필수 지식

조건문, 랜덤값,반복문 실수하는 부분들

by 생존개발 2022. 9. 30.

switch~case문에서 break;를 절대 까먹지말자!!!

break;가 없는 경우 case를 실행하고 그 밑에 있는 case까지 전부 진행하게 된다!!

 

랜덤값을 사용할 때는 아래와 같이 import를 해줘야 함

import java.util.Random;

public class InputTest {
    public static void main(String[] args) {
        Random input = new Random();

        System.out.println( input.nextInt() );        // 1483266798 (int 표현범위 사이값)
        System.out.println( input.nextInt(10) );      // 1 (0 <= 값 < 10)
        System.out.println( input.nextInt(10) + 1 );  // 3 (1 <= 값 < 11)
        System.out.println( input.nextInt(10) * (-1) );  // -6 (-10 < 값 <= 0)
        System.out.println( input.nextBoolean() );    // false (true or false)
        System.out.println( input.nextLong() );       // -7488279853580653828 (long 표현범위 사이값)
        System.out.println( input.nextFloat() );      // 0.5873405 (float 표현범위 사이값)
        System.out.println( input.nextDouble() );      // 0.4279275246744185 (double 표현범위 사이값)
    }
}

double을 사용할 때는 잘 생각해야 함

> 주사위 6 랜덤값에 사용하려면  "변수 < input.nextDouble()*6 +1"같은 방식이 필요함

> 이런식으로 int가 아니라 double로 사용해야하는 경우는 충분히 조건을 고려하자       

 

반복문

 

while문과 for문을 충분히 다룰 수 있게되면

그 안에서 사용해야할

 

* continue; 뒤에 작성된 반복문 케이스를 생략할 수 있음

* break; // 반복문 종료구문

l* ooping; // 처음으로 돌아가 반복실행할 수 있음

 

위3가지를 잘 활용해보자 (알고리즘에서 많이 활용)

'필수 지식' 카테고리의 다른 글

call by reference의 의미  (0) 2022.10.07
enum 사용시 기억할 점  (0) 2022.10.07
입출력 메소드 / 자료형 변환 / 연산자에서 자주쓰는 것  (1) 2022.09.30
변수와 상수  (2) 2022.09.22
자바 기초  (0) 2022.09.22