当前位置: 代码迷 >> Web前端 >> switch中的变量声名和使用的有关问题解决方案
  详细解决方案

switch中的变量声名和使用的有关问题解决方案

热度:181   发布时间:2012-11-23 00:03:43.0
switch中的变量声名和使用的问题解决方案

首先错误代码:

public static void main(String[] args) {
		int type = 2;
		switch (type) {
		case 0:
			int i = 0;
			System.out.println(type);
			break;
		case 1:
			int i = type;
			System.out.println(i);
			break;
		case 2:
			int i = type;
			System.out.println(i);
			break;
		case 3:
			int i = type;
			System.out.println(i);
			break;
		}
	}

?解决方法:

??? 使用java中的大括号来限定case中声明的变量的作用域

public static void main(String[] args) {
		int type = 2;
		switch (type) {
		case 0: {
			int i = 0;
			System.out.println(type);
			break;
		}
		case 1: {
			int i = type;
			System.out.println(i);
			break;
		}
		case 2: {
			int i = type;
			System.out.println(i);
			break;
		}
		case 3: {
			int i = type;
			System.out.println(i);
			break;
		}
		}
	}
  相关解决方案