The command switch: making choices in Java


In the article about the while loop in our online Progressive Java course, we show how to create a simple menu.
But Java has a specific feature for this purpose, which allows us to choose something, depending on what we typed, is the command switch.

We put several options and various commands within the command switch, all the possibilities of our application or any options or paths that can take our programs.
O comando switch: fazendo escolhas em Java

The switch will function as a real switch, because depending on the input you give it, it will trigger only right (s) statement (s) from among you provided.

It's as if you created a menu or menu, and with the switch you will want to choose what.

Statement and Command Syntax switch


In Java, we use the command switch and declare as follows:

switch( option )
{
    case option1:
            commands in case the option1 is the chosen one
            break;
    
    case option2:
            commands in case the option2 is the chosen one
            break;
    
    case option3:
            commands in case the option3 is the chosen one
            break;
    
    default:
            commands in case the any of the case options is chosen

}


The variable 'option' is usually an integer or character (can also be byte or short), the user enters through the Scanner class.
If 'option' receive 'option1' as input, the codes are contained in the 'case option1' that will run.
If 'option' receive 'option2' as input, the codes are contained in the 'case option2' that will run.
If 'option' receive 'option3' as input, the codes are contained in the 'case option3' that will run.
If 'option' receive anything other than 'option1', 'option2' or 'option3', are the codes contained in 'default' will be executed.


Example of use:

Let's create a calculator that does basic operations using the command switch.
It's a simple Java application that receives 3 inputs: two numbers and one character.
This character may be '+', '-', '*' or '/', and represent the mathematical operation you want to perform between numbers.

Look the Java code:



import java.util.Scanner;

public class switchTest {
    public static void main(String[] args) {
        float number1, number2;
        char operator;
        Scanner input = new Scanner(System.in);
        
        System.out.print("Choose the math operation [+ - * / ]: ");
        operator = input.nextLine().charAt(0);
        
        System.out.print("Type the first number: ");
        number1 = input.nextFloat();
        System.out.print("Type the second number: ");
        number2 = input.nextFloat();
        System.out.println();
        
        switch( operator )
        {
            case '+':
                System.out.printf("%.2f + %.2f = %.2f", number1, number2, number1 + number2);
                break;        
                
            case '-':
                System.out.printf("%.2f - %.2f = %.2f", number1, number2, number1 - number2);
                break;
                
            case '*':
                System.out.printf("%.2f * %.2f = %.2f", number1, number2, number1 * number);
                break;
                
            case '/':
                System.out.printf("%.2f / %.2f = %.2f", number1, number2, number1 / number2);
                break;
            
            default:
                System.out.printf("You typed an invalid option");        
            
        }
        

    }
}




If the 'option' is a char, put single quotation marks ' ', if string put double quotation marks " " and if is a number, is not required to put any quotes.

The actual operation of the command switch: without the break statement

We omitted purposely important information.
Is only conducted a 'case' at a time because there's a 'break' statement in each command contained within the 'case'.

In fact, the switch selects the 'case' through 'option' and makes all the 'case' to run from that.
The following example illustrates the real functioning of the switch statement in Java, try typing the vowel 'a':



import java.util.Scanner;

public class switchTest2 {
    public static void main(String[] args) {
        char vowel;
        Scanner input = new Scanner(System.in);
        
        System.out.print("Type a lowercase vowel: ");
        vowel = input.nextLine().charAt(0);
        
        
        switch( vowel )
        {
            case 'a':
                System.out.println("You are in the case of vowel 'a'");
            case 'e':
                System.out.println("You are in the case of vowel 'e'");
            case 'i':
                System.out.println("You are in the case of vowel 'i'");
            case 'o':
                System.out.println("You are in the case of vowel 'o'");
            case 'u':
                System.out.println("You are in the case of vowel'u'");
        
            default:
                System.out.println("You didn't type a lowercase vowel");        
            
        }
        

    }
}




Example usefulness of the command switch without break 

At first, seems strange that property of the command switch 'rotate' the squeegees cases.
However, it is very handy and well used, will only help us. And if you do not need, simply place a break.

Let's take the last example and make it more robust proof that users try to enter uppercase vowels.
It is a practice quite common in Java, it is essential that you learn:



import java.util.Scanner;

public class switchTest3 {
    public static void main(String[] args) {
        char vowel;
        Scanner input = new Scanner(System.in);
        
        System.out.print("Type one vowel: ");
        vowel = input.nextLine().charAt(0);
        
        
        switch( vowel )
        {
            case 'a': case 'A':
                System.out.println("You typed 'a' or 'A' ");
                break;
            
            case 'e': case 'E':
                System.out.println("You typed 'e' or 'E' ");
                break;
                
            case 'i': case 'I':
                System.out.println("You typed 'i' or 'I' ");
                break;
                
            case 'o': case 'O':
                System.out.println("You typed 'o' or 'O' ");
                break;
                
            case 'u': case 'U':
                System.out.println("You typed 'u' or 'U' ");
                break;

            default:
                System.out.println("You didn't type a lowercase vowel !");
            
        }
        

    }
}



Note that we are accumulating the case lowercase and uppercase of each vowel to generate the same command. This is a common practice. In this case, the command is print.

Another example of the control switch without break

Suppose you delayed an account. Each month you fail to pay will be charged 1% interest in the initial value.
That is, if you delay a month will pay 1%. If delayed 3 months, will pay 3% etc..
Suppose you can delay no more than 5 months.

The program asks as input two values:
- A float: with the value of its initial debt (value_i)
- An integer: from 0 to 5, which are the months of delay.

Our Java program would look like this:



import java.util.Scanner;

public class switchTest4 {
    public static void main(String[] args) {
        float value_i, value_f, interestRate=0;
        int months;
        Scanner input = new Scanner(System.in);
        
        System.out.print("What's the inital value of the debt: ");
        value_i = input.nextFloat();
        
        System.out.print("How many months will you be late [0-5]?: ");
        months = input.nextInt();
        
        switch( months )
        {
            case 5:
                interestRate++;
            case 4:
                interestRate++;
            case 3:
                interestRate++;
            case 2:
                interestRate++;
            case 1:
                jinterestRate++;
                break;
            default:
                System.out.println("You did not enter a valid months");
            
        }
        System.out.println("Interest rate: "+interestRate+"%");
        value_f=( (1 + (interestRate/100))*value_i);
        System.out.printf("Final debt value: R$ %.2f", value_f);

    }
}



If you fall in case 5, will tell all case until the break, adding interest = 5
If you fall in case 4, will tell all case until the break, adding interest = 4
Thus, similarly to case 3, 2 and case 1.

That is, we use the fact that the case go on accumulating.

Exercise:
Create a program that receives an integer of 1 to 12, representing the months of the year and return the number of days in the month.
Use switch and not use break command. Accumulate the case.

No comments: