Java selection control syntax: if, switch

Java uses if and switch syntax for select control. The basic use of if-else and if-else-if syntax is shown below.

if-else

if(condition) {
	sentence 1;
} else {
	sentence 2;
}

if-else-if

if(condition) {
	sentence 1;
} else if(condition) {
	sentence 2;
} else if(condition) {
	sentence 3;
} else {
	sentence n;
}

if Basic example

In addition to Java, most programming languages support if, if-else, and switch syntax. The following example is a program that accepts data from a user, converts the data to an integer, compares it with data through an if condition, and outputs the message.

class IfElse {
	public static void main(String args[]) {
		int month = Integer.parseInt(args[0]);
		//In the execution command, data is input from the user, converted to an integer, and stored in month
		String MtoS;

		if(month == 12 || month == 1 || month == 2) {
			MtoS = "winter";
		} else if(month == 3 || month == 4 || month == 5) {
			MtoS = "spring";
		} else if(month == 6 || month == 7 || month == 8) {
			MtoS = "summer";
		} else if(month == 9 || month == 10 || month == 11) {
			MtoS = "autumn";
		} else {
			MtoS = "There is no corresponding season.";
		}

		System.out.println( month + "month is " + MtoS);

	}
}

Basic usage and examples of switch

switch(Equation) {
	case value1:
		sentence;
		break;
	case value2:
		sentence;
		break;
	case value3:
		sentence;
		break;
	default:
		Sentence to be treated implicitly;
}

Below is a simple example of outputting rock-paper-scissors using a switch.

class Switch {
	public static void main(String args[]) {
		for(int i=1; i<5; i++) {
			switch(i) {
				case 1:
					System.out.println( i + " : Rock" );
					break;
				case 2:
					System.out.println( i + " : Paper" );
					break;
				case 3:
					System.out.println( i + " : Scissors" );
					break;
				default:
					System.out.println( i + "is not a value between 1 and 3" );
			}
		}
	}
}

Share This Post

댓글 남기기

이메일은 공개되지 않습니다. 필수 입력창은 * 로 표시되어 있습니다

Latest Post