能java用case和switch举个简单的例子吗?

简单的就行注解下意思
2025-02-24 21:00:10
推荐回答(2个)
回答1:

public static void main(String[] args) {
int i = 1;
switch (i) {
case 1://如果switch (i)中的i=1 的时候执行以下程序
System.out.println(1);
break;//执行到break 如果不写会顺序向下执行System.out.println(2);
case 2://如果switch (i)中的i=2 的时候执行以下程序
System.out.println(2);
break;
default://其他 即switch (i) 中的i 不等于case 1 case 2 中的 1 2那么就执行下面的程序
System.out.println("other");
break;
}
}

回答2:

public static int get(int n){
int count ;
switch (n) {
case 1:
count = 1 ;
break;
case 2:
count = 2 ;
break;
default:
count = 0 ;
break;
}
return count ;
}