본문 바로가기

콤퓨타/Programming) 왕초보 자바

20. (Loops and Conditions) Switch Fallthrough

Switch Fallthrough


break; 

it breaks out of the switch statement at that point. 

 

when we don't have break statement in a switch, when we just start somehwere and then do all the options afterwards. 

we say we're falling through to the other case statement and this is sometimes useful so it's perfectly valid to have a switch statement with no breaks in it or only with breaks in certain places. 

 

 

 

 

 

일단 기본으로 코드를 짜면 이렇게 나온다. 

package application;

import java.util.Scanner;

public class App {
	
	public static void main(String[] args) {
		
		System.out.println("Do you want to proceed (y/n): ");
		Scanner scanner = new Scanner(System.in);
		String input = scanner.nextLine();
		scanner.close(); 
		switch (input) { 
		case "y":
			System.out.println("Proceeding...");
		break;
		
		case "n":
			System.out.println("Not proceeding.");
		break; 
		
		default:
			System.out.println("Unrecognized option");
			break; 	
		}
	}
}

 

 

y나 n 중에 하나를 고르는 것이므로 간만에 string 등판 ㅇㅇ

여기까지는 방금전까지 한 내용. 

하지만 저 break; 들이 없다면? 

 

예전부터 궁금한 내용이었는데 이번에 해보게 되었다. 

break;

가 없다면 switch 아래에 있는 코드를 다 읽어버릴수 있다. 

 

package application;

import java.util.Scanner;

public class App {

	public static void main(String[] args) {

		System.out.println("Do you want to proceed (y/n): ");
		Scanner scanner = new Scanner(System.in);
		String input = scanner.nextLine();
		scanner.close();

		switch (input) {
		case "y":
			System.out.println("Proceeding...");
			// break;

		case "n":
			System.out.println("Not proceeding.");
			// break;

		default:
			System.out.println("Unrecognized option");
			// break;
		}

	}

}

 

y 를 눌렀을 때 , y를 매칭하여 읽어내고, 그 이후로 나오는 코드도 모두 출력한다

n을 눌렀을 때 , y는 무시하고, n을 매칭하 여 읽어내고, 그 이후로 나오는 코드도 모두 출력한다

그 외를 눌렀을때 , y는 무시, n도 무시, 나머지 코드를 모두 출력한다. 

 

 

 

break; 를 기점으로 그 다음 코드는 읽어서 실행하지 않지만, 

때때로 break를 생략해서 일부로 switch fallthrough가 발생하도록 만들기도 한다. 

 

 

해피코딩