switch语句
int a = 1,b =2;
switch(a+b){
case 1:
System.out.print(1);
case 3:
System.out.print(3);
case 4:
System.out.print(4);
default:
System.out.print(5);
}
先执行 a+b 得出值 3
找到相对应case 3,然后继续向下
执行执行所有的语句,因为没有 break
在线免费视频教程推荐:java教学视频
结果:
345
int a = 2, b = 34;
switch(a + b){
case 5:
System.out.println(5);
break;
case 6:
System.out.println(6);
break;
default:
System.out.println(12);
}
执行 a + b ,得出 36
执行 default
结果:
12
判断月份
Scanner a = new Scanner(System.in);
System.out.print("please input a month:");
int month = a.nextInt();
switch(month){
case 1: case 2: case 3:
System.out.println("Spring");
break;
case 4: case 5: case 6:
System.out.println("Summer");
break;
case 7: case 8: case 9:
System.out.println("Autumn");
break;
case 10: case 11: case 12:
System.out.println("Winter");
break;
default:
System.out.println("fasle");
}
Scanner a = new Scanner(System.in);
System.out.print("please input a month:");
int month = a.nextInt();
switch(month){
case 1:
case 2:
case 3:
System.out.println("Spring");
break;
case 4:
case 5:
case 6:
System.out.println("Summer");
break;
case 7:
case 8:
case 9:
System.out.println("Autumn");
break;
case 10:
case 11:
case 12:
System.out.println("Winter");
break;
default:
System.out.println("fasle");
}
两个方式一样,但switch语句内,的多个语句,即语句块,并不需要加花括号,因为碰到break语句跳出,否则继续执行下去。
循环语句
求1000以内的素数
int j;
for (int i = 0; i < 1000; i++) {
for (j = 2; j < i; j++)
if (i % j == 0)
break;
if (j == i)
System.out.println(i);
}
结果:
2
3
5
…
当然上面犯了一个明显的错误,最外层的循环应该是<=1000,虽然并不影响什么,但要铭记。
for (int i = 0; i < 1000; i++) {
if(i == 2)
System.out.println(2);
for (int j = 2; j < i; j++) {
if(i % j == 0)
break;
if(j == i - 1 )
System.out.println(i);
}
}
相关文章教程推荐:java零基础入门