항해99/Java 문법 뽀개기

자바문법뽀개기(6) - 조건문

숲별 2022. 9. 25. 02:17
728x90

연산자와 마찬가지로 다른 언어와 같으므로 패스 가능.

 

<if 문>

public class Main {
    public static void main(String[] args) {
        int check = 100;
        int num1 = 150;
        if(num1 > check){
            System.out.println("100보다 큰 수 입니다.");
        }else if(num1 >50){
            System.out.println("50보다 큰 수 입니다. 100보다 작거나 같습니다.");
        }

    }
}

 

 

<switch문>

public class Main {
    public static void main(String[] args) {
        char score = 'A';
        switch (score){
            case 'A':
                System.out.println("A등급 축하합니다.");
                break;
            case 'B':
                System.out.println("B등급");
                break;
            case 'C':
                System.out.println("C등급");
                break;
            default:
                System.out.println("C보다 아래 등급입니다.");
        }

    }
}

=>

A등급 축하합니다.

 

public class Main {
    public static void main(String[] args) {
        char score = 'B';
        switch (score){
            case 'A':
                System.out.println("A등급 축하합니다.");                
            case 'B':
                System.out.println("B등급");                
            case 'C':
                System.out.println("C등급");
            default:
                System.out.println("C보다 아래 등급입니다.");
        }
    }
}

=>B등급
C등급
C보다 아래 등급입니다.

 

break 빼면 'A'는 아니니 넘어가고 

'B' 맞아서 들어감.

근데 break없으니까 그 다음도 다 들어감.

 

<삼항연산자>

public class Main {
    public static void main(String[] args) {
        int a=5;
        String result = (a<10) ? "10보다 작습니다." : "10보다 큽니다.";
        System.out.println(result);
    }
}

=>10보다 작습니다.

 

(조건) ? 참: 거짓

 

<퀴즈>

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int score = sc.nextInt();
    }
}

Scanner에 커서 두면 Alt+Enter해서 import java.util.Scanner 쓸 수 있다.

스캐너에 시스템 인풋을 받을 거야라는의미

sc.nextInt()는 다음에(엔터치기 전까지) 들어오는 숫자를 받을 거야라는 의미

 

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int score = sc.nextInt();
        if(score<=100 && score>90) {
            System.out.println("A등급입니다.");
        } else if(score<=90 && score>80){
            System.out.println("B등급입니다.");
        } else if(score<=80 && score>70){
            System.out.println("C등급입니다.");
        }else{
            System.out.println("F등급입니다.");
        }

    }
}

밑에 터미널에 값을 입력해줘야 마저 실행된 아니면 계속 돌아가기만...

=>A등급입니다.