switch只能针对某个表达式的值作出判断,从而决定程序执行哪一段代码,遇到break;结束循环。
编写代码实现如下内容:if语句实现考试成绩分等级(使用switch语句)。
[90-100] A等。
[80-90) B等。
[70-80) C等。
[60-70) D等。
[0-60) E等。
请根据给定成绩,输出对应的等级。
说明:"["表示包含,")"表示不包含
public static void main(String[] args) {
// 键入学生成绩
char c;
while (true) {
System.out.println("请输入学生成绩");
@SuppressWarnings("resource")
int studentScore = new Scanner(System.in).nextInt();
if (studentScore >= 90 && studentScore <= 100) {
c = 'A';
break;
} else if (studentScore >= 80 && studentScore < 90) {
c = 'B';
break;
} else if (studentScore >= 70 && studentScore < 80) {
c = 'C';
break;
} else if (studentScore >= 60 && studentScore < 70) {
c = 'D';
break;
} else if (studentScore >= 0 && studentScore < 60) {
c = 'E';
break;
} else {
System.out.println("数值超出范围,请重新输入!");
}
}
switch (c) {
case 'A':
System.out.println("A");
break;
case 'B':
System.out.println("B");
break;
case 'C':
System.out.println("C");
break;
case 'D':
System.out.println("D");
break;
case 'E':
System.out.println("E");
break;
default:
System.out.println("出现错误!");
}
}
}
数组:
int [ ] x =new int [];
int [ ] x ={1,2,3,4};
数组获取最值代码实现:
public static void main(String [ ] args){
int [ ] a= {5,1,3,8};
int max =a[0];
for(int i =;i<a.length;i++){
if(a[i]>max)
max=a[i];
}
syso(max);
}
二维数组:
①int [ ] [ ] arr =new int[3][4];
即二维数组长为3,每个元素长度为4;3行4列。
②int [ ] [ ] arr=new int [3] [ ](列数不确定)
二维数组的遍历:
public static void main (String [ ] args){
int [ ] [ ] arr={{1,2,3},{4,5},{6,7,8,9,0}};
for(int i=0;i<arr.length;i++){
for(intj=0;j<arr[i].length;j++){
syso(arr[i][j]);
}
}
}
数组元素逆序 (就是把元素对调):
public static void main(String[] args) {
// 数组元素逆序 (就是把元素对调)
int arr[] = { 1, 2, 4, 5, 6, 7, 8 };
for(int a = arr.length-1 ; a >= 0 ; a--){
System.out.print(arr[a]+" ");
}
}