Java : Control flow statements

m_ngyeong·2024년 3월 5일
0

Java

목록 보기
6/6
post-thumbnail

☕️ Java

Conditional statement(조건문)

조건문은 프로그램이 Boolean expression(부울 표현식)의 값에 따라 다른 계산을 수행할 수 있도록 하는 구성이다. true이면 프로그램은 한 번의 계산을 수행하고, false이면 프로그램은 또 다른 계산을 수행한다.

The single if-case

조건문의 가장 간단한 형태는 if 키워드, 괄호로 묶인 부울 표현식, 중괄호로 묶인 본문으로 구성된다.

if (expression) {
    // body: do something
}

표현식이 true이면 코드 블록 내의 명령문이 실행되고, 그렇지 않으면 프로그램이 이를 건너뛴다.
조건의 식이 단일 boolean유형 변수인 경우,

boolean bool = true; // or false
if(bool){ // or !bool
    System.out.println("Hello world!");
}

로 사용할 수 있다.

The if-else-cases

int num = ...; // the num is initialized by some value

if (num % 2 == 0) {
    System.out.println("It's an even number");
} else {    
    System.out.println("It's an odd number");
}

이 표현식은 true이면 첫 번째 코드 블록이 실행되고, 그렇지 않으면 두 번째 코드 블록이 실행된다.

The if-else-if-cases

조건문의 가장 일반적인 형태는 여러 조건과 else-if분기로 구성된다.

long dollars = ...; // your budget

if (dollars < 1000) {
    System.out.println("Buy a laptop");
} else if (dollars < 2000) {
    System.out.println("Buy a personal computer");
} else if (dollars < 100_000) {
    System.out.println("Buy a server");
} else {
    System.out.println("Buy a data center or a quantum computer");
}

여러 분기가 있는 조건문은 노드가 boolean expressions(부울 표현식)으로 구성되고 각 분기는 true 또는 false로 표시되는 의사결정 트리를 생성한다.
true분기는 실행될 명령문 블록으로 이어지고 false분기는 확인할 다음 조건으로 이어진다. 마지막 false분기는 "다른 모든 경우"를 의미한다.


Decision tree for buying a computer

📌 조건에 관해 이야기할 때 "control flow statements(제어 흐름 명령문)"이라는 용어를 사용. 제어 흐름은 프로그램의 다양한 부분이 실행되는 순서.

One-line condition with ternary operator

The ternary operator(삼항 연산자)

삼항 연산자는 조건을 평가하고 실행할 두 가지 경우 중 하나를 선택하는 연산자이다. 조건 연산자라고도 하며, if-then-else문의 형태로 간주될 수 있다.

result = condition ? trueCase : elseCase;

조건은 true 또는 false로 평가되는 부울 표현식이다. 표현식이 true이면 삼항 연산자는 trueCase를 평가하고, 그렇지 않으면 elseCase를 평가한다.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        // Read the input number
        int number = scanner.nextInt();

        // Write a one-line condition using ternary operator to check if the number is even or odd
        String result = number%2==0?"even":"odd";
        System.out.println(result);
    }
}


참고문헌,
https://hyperskill.org/tracks/8

profile
사용자 경험 향상과 지속적인 성장을 추구하는 프론트엔드 개발자 ʚȉɞ

0개의 댓글