In Java you can make choices with a switch-statement. Actually, you ask the computer something.

switch statement

 

theory

  • start with switch: switch + ( + variable + ) + {
    switch (variable) {
  • For the first question: case +  value + : + break;
    case 1:
    	// you end up here when the variable is 1
    	break;
  • For the second question use: case +  value + : + break;
    case 2:
    	// you end up here when the variable is 2
    	break;
  • (OPTIONAL) If the variable doesn’t equal the above values: default
    default:
    	//you end up here when it doesn't equal the variable
  • close the statement with a }

EXAMPLE 1

package Switch;

import java.util.Scanner;

public class Switch {

	void start() {
		Scanner in = new Scanner(System.in);
		int i = in.nextInt();

		switch (i) {
		case 1 - 2:
			System.out.println("number is 1 or 2");
			break;
		case 4:
			System.out.println("number is 4");
			break;
		case 5:
			System.out.println("number is 5");
			break;
		default:
			System.out.println("no option");
		}
	}

	public static void main(String[] args) {
		new Switch().start();

	}

}

example 2

package Switch;

import java.util.Scanner;

public class Switch {

	void start() {
		Scanner in = new Scanner(System.in);
		int i = in.nextInt();

		switch (i) {
		case 1:
		case 2:
			System.out.println("number is 1 or 2");
			break;
		case 4:
			System.out.println("number is 4");
			break;
		case 5:
			System.out.println("number is 5");
			break;
		default:
			System.out.println("no option");
		}
	}

	public static void main(String[] args) {
		new Switch().start();

	}

}

example 3

package Switch;

import java.util.Scanner;

public class Switch {

	void start() {
		Scanner in = new Scanner(System.in);
		int i = in.nextInt();

		switch (i) {
		case 1: case 2:
			System.out.println("number is 1 or 2");
			break;
		case 4:
			System.out.println("number is 4");
			break;
		case 5:
			System.out.println("number is 5");
			break;
		default:
			System.out.println("no option");
		}
	}

	public static void main(String[] args) {
		new Switch().start();

	}

}

SWITCH- VS IF/ELSE STATEMENT