개발 완료

Java - Switch문으로 계절 나타내기

페페로니피자 2020. 3. 13. 23:42
반응형

I am going to talk about Switch statement today.

 

 

Purpose

  • Indicate a season when client enter a month

import java.util.Scanner;

public class study {
    public static void main(String[] args) {
        System.out.println("What month is now?");

        Scanner scanner = new Scanner(System.in);
        int month = scanner.nextInt();

        switch (month) {
            case 3: case 4: case 5: {
                System.out.println("This is spring season");
                break;
            }

            case 6: case 7: case 8: {
                System.out.println("This is summer season");
                break;
            }

            case 9: case 10: case 11: {
                System.out.println("This is autumn season");
                break;
            }

            default: {
                System.out.println("This is winter season");
                break;
            }
        }
    }
}

Switch statement

 

We are only able to put String, Int type data to switch expression. 

And also only able to put String, Int, Constant type data to case value.

Case values should be not duplicated.

If we don't put break;, it is going to go through whole code untill it meets final parenthesis.

 

When we have to put many choices, using if ~ else is not recommended. Becasue we have to put too much if else statement.


Result

 

반응형