9. SWITCH STATEMENT

Switch::::::
Switch statement provides an easy way to dispatch execution to different parts of your of your code based on the value of an expression. It often provides a batter alternative then of if-else-if statements.
General form:
Switch(exprassion){
    case value1:
             //statement
            Break;
    case value2:
             //statement
             Break;
    default:
            //default statement
}
The expression must be of type byte, short, int, or char, each of the values specified in the case statements must be of a type compatible with the expression. Each case.value must be a unique literal. Duplicate case values are not allowed.
The switch statement works like this. The value of the expression is compared with each of the literal values in the case statements. If a match is found, the code sequence following that case statement is executed. If none of the constant matches the value of the expression, then the default statement executed. However, the default statement is optional. If no case matches and no default is present, then no further action is taken.
The break statement is used inside the switch to terminate a statement sequence. Lt’s see an example
import java.util.Scanner;
public class theswitch {
      public static void main(String args[]){
        Scanner pavel = new Scanner(System.in);
        System.out.println("Enter how much book you have");
        int mostafij = pavel.nextInt();
        
        switch(mostafij){
            case 0:
              System.out.println("I have no books");
              break;
            case 1:
                  System.out.println("I have "+mostafij+" book");
                  break;
            case 2:
                  System.out.println("I have "+mostafij+ "books");
                  break;
            case 3:
                  System.out.println("I have "+mostafij+" books");
                  break;
            case 4:
                  System.out.println("I have "+mostafij+" books");
                  break;
            case 5:
                  System.out.println("I have "+mostafij+" books");
                  break;
                default:
                  System.out.println("I have not counted them");
      }
      }
}
Now you see that first this program wants to know how much books you have. You have to input that number and it will output “you have numbers of book”. But if you input a number that is larger than 5 it will print default.
Thank you very much. We will see in next tutorial.

Penulis : Mostafij ~ Sebuah blog yang menyediakan berbagai macam informasi

Artikel 9. SWITCH STATEMENT ini dipublish oleh Mostafij pada hari Tuesday, April 9, 2013. Semoga artikel ini dapat bermanfaat.Terimakasih atas kunjungan Anda silahkan tinggalkan komentar.sudah ada 0 komentar: di postingan 9. SWITCH STATEMENT
 

0 comments:

Post a Comment