您的位置:首页 > 编程语言 > C语言/C++

Java和C++中的switch语句

2012-03-16 23:32 531 查看
在Java和C++中,switch语句表示有多种条件可供选择,在Java和C++中用法基本相同。

switch语句的格式如下:

switch (expression - E){

case constant - expression -1: statement -1;break;

case constant - expression -2: statement -2;

case constant - expression -3: statement -3;return;

default:throw something;

}

对于switch语句中的每个case,要用break,return或者throw来进行结束。

下面以Java中的一个程序为例,来说明switch语句的用法和break,return,throw使用注意事项。

public class Switch {
	public static void main(String args[]){
		int currentValue=Integer.parseInt(args[0]);
		int colour=currentValue;
		
		switch (colour){
		case 0:System.out.println("red");
		break;
		case 1:System.out.println("amber");
		return;
		case 2:System.out.println("green");
		default:System.out.println("error");
		}
		System.out.println("out of switch but still in main()");
	}
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: