Java Switch Statement With Example

 


First, understanding the switch structure.



import java.util.Scanner;

public class Main {
	
	public static void main(String[] args) {
		
		Scanner scan = new Scanner(System.in);
		
		System.out.println("1-Balance");
		System.out.println("2-Balance increased");
		System.out.println("3-Balance withdrawal");
		System.out.print("Enter Operation Number: ");
		
		int number = scan.nextInt();
		
		switch(number) { //If the value we enter is equal to which of the cases, that case works.
		
		case 1:
			System.out.println("Your balance 100$");
			break; //We have to write this, otherwise, the code continues and whenever break is executed, the code exits the switch.
		
		case 2:
			System.out.println("Your balance increased by $100");
			break;
		
		case 3:
			System.out.println("You have withdrawn $100 from your balance");
			break;
		
		default: // This works if a wrong value is entered
			System.out.println("Your balance 100$");
			break;
		}
	
	}
	
}


Outputs






Second, let's develop the project a little.


import java.util.Scanner;

public class Main {
	
	public static void main(String[] args) {
		
		float myBalance = 1453.0f;
		
		Scanner scan = new Scanner(System.in);
		
		System.out.println("1-Balance");
		System.out.println("2-Balance increased");
		System.out.println("3-Balance withdrawal");
		System.out.print("Enter Operation Number: ");
		
		int number = scan.nextInt();
		
		switch(number) {
		
		case 1:
			System.out.println("Your balance $" + myBalance);
			break;
		
		case 2:
			System.out.print("Increased balance: $");
			
			float increaseBalance = scan.nextFloat();
			
			System.out.println("Your balance increased by $" + increaseBalance);
			System.out.println("Your balance $" + (myBalance + increaseBalance));
			break;
		
		case 3:		
			System.out.print("Withdrawn balance: $");
			float withdrawBalance = scan.nextFloat();
			
			System.out.println("You have withdrawn $" + withdrawBalance +" from your balance");
			System.out.println("Your balance $" + (myBalance - withdrawBalance));
			
			break;
		
		default:
			System.out.println("Your balance $" + myBalance);
			break;
		}
	
	}
	
}








Good Bye Everyone


Image Resource: http://d1jnx9ba8s6j9r.cloudfront.net/blog/wp-content/uploads/2019/07/Switch-case-in-java.jpg

0 Comments