跳转到内容

Java 编程/关键字/switch

来自维基教科书,开放的书本,用于开放的世界

switch 是一个 Java 关键字。

它是一个基于数字的分支操作。该“数字”必须是 charbyteshortint 原生类型。

语法

switch ( <integer-var> )
{
   case <label1>: <statements>;
   case <label2>: <statements>;
   ...
   case <labeln>: <statements>;
   default: <statements>;
}

当 <integer-var> 值与其中一个 <label> 匹配时,则:匹配的标签后的语句将被执行,包括以下标签的语句,直到 switch 块的末尾,或直到遇到 break 关键字。

例如

Computer code
int var = 3;
switch ( var )
{
   case 1: 
      System.out.println( "Case: 1" );
      System.out.println( "Execute until break" );
      break;		  	
   case 2: 
      System.out.println( "Case: 2" );
      System.out.println( "Execute until break" );
      break;
   case 3:
      System.out.println( "Case: 3" );
      System.out.println( "Execute until break" );
      break;  	
   case 4:
      System.out.println( "Case: 4" );
      System.out.println( "Execute until break" );
      break;      
   default:
      System.out.println( "Case: default" );
      System.out.println( "Execute until break" );
      break;	      
}

以上代码的输出为

Case: 3
Execute until break

相同的代码可以用 if-else 块编写"

Computer code
int var = 3;
if ( var == 1 ) {
   System.out.println( "Case: 1" );
   System.out.println( "Execute until break" );
} else if ( var == 2 ) {
   System.out.println( "Case: 2" );
   System.out.println( "Execute until break" );
} else if ( var == 3 ) {
   System.out.println( "Case: 3" );
   System.out.println( "Execute until break" );
} else if ( var == 4 ) {
   System.out.println( "Case: 4" );
   System.out.println( "Execute until break" );
} else {
   // -- This is the default part -- 
   System.out.println( "Case: default" );
   System.out.println( "Execute until break" );
}


另请参见

华夏公益教科书