Pitch your project

Random text






Blogs

0    
By admin Category Uncategorized, Posted February 9th, 2016
Switch statement

The IF/ELSE statement allow for flexibility in writing conditional code. However we can write conditional code more effective by the use of Switch statements.

Switch statement examines a single value and then compares it to multiple possibilities.It enables for the control of flow of execution based on when the 2 values match.

Below is a snippet of a code implementing Switch statements.

'public class Switch {
    public static void main(String[]args){
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a new number: ");
        int input= Integer.parseInt(sc.nextLine());

        switch(input){
            case 1:
                System.out.println("January");
                break;
            case 2:
                System.out.println("February");
                break;
            case 3:
                System.out.println("March");
                break;
            case 4:
                System.out.println("April");
                break;
            case 5:
                System.out.println("May");
                break;
            case 6:
                System.out.println("June");
                break;
            case 7:
                System.out.println("July");
                break;
            case 8:
                System.out.println("August");
                break;
            case 9:
                System.out.println("September");
                break;
            case 10:
                System.out.println("October");
                break;
            case 11:
                System.out.println("November");
                break;
            case 12:
                System.out.println("December");
                break;
            default:
                System.out.println("The month is not recognized");
        }
    }
}'

The code gets user input and depending on that returns what month the number represents.

KeyWords

  • Break: a call to the break statement means that we are finished with the switch statement and execution goes to the last parentheses
  • Default: Executed if none of the other cases are true

Posted by Teddy Maina

Leave a Reply

Your email address will not be published. Required fields are marked *