Java development for beginners 7. Switch statement
Another way to control the flow of your programms is with a switch statement. A switch statement gives you the option to test for a range of values for your variables. They can be used instead of long, complex if- else if statements.
The structure of the switch statement is this:
switch ( variable_to_test ) { case value: code_here; break; case value: code_here; break; default: values_not_caught_above; break; }
You start with the word switch, followed by the variable you want to check, between round brackets. The other parts of the switch statement all go between two curly brackets. For every value that you want to check, you need the word case. You then have the value you want to check for: case value:
After case value comes a colon. You then write the code that you want execute. The keyword break is needed to break out of each case of the switch statement.
The default value at the end is optional. It can be included if there are other values that can be held in your variable but that you haven't checked for elsewhere in the switch statement.
Below we have the code for the video tutorial:
package com.edu4java.tutorial7; import java.util.Scanner; public class Tutorial7 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Option menu"); System.out.println("1. Addition(x+y)"); System.out.println("2. Subtraction (x-y)"); System.out.println("3. Multiplication (x*y)"); System.out.println("4. Division (x/y)"); System.out.println(); System.out.println("Insert your option:"); int option = scanner.nextInt(); System.out.println("Insert the first number"); int x = scanner.nextInt(); System.out.println("Insert the second number"); int y = scanner.nextInt(); int result = 0; switch (option) { case 1: result = x + y; break; case 2: result = x - y; break; case 3: result = x * y; break; case 4: result = x / y; break; default: System.out.println("error in the option."); break; } System.out.print("the result is:"); System.out.println(result); } }
<< Previous | Next >> |