索引贴:http://www.mcbbs.net/thread-138969-1-1.html
这一章的内容比较少,只是为了补完条件语句,等下还有一章。
条件语句:http://www.mcbbs.net/thread-141338-1-1.html
之前我们说了条件语句中的if,现在我们来说说另一个条件语句switch,英文好一点的同学知道,if是如果的意思,而switch有开关的意思。
如果把if语句翻译成我们能的语言就是:如果怎样就。而嵌套则是:如果怎样就如果怎样就。“就”(判断完成后)的后面还是一个判断。
而switch呢?如它的翻译一样,这是一个开关。
接下来我们将为大家详细的说明一下switch的用法,开关之意就很好理解了。
基本格式
- switch(变量)
- {
- case 条件1:命令1;
- break;
- case 条件2:命令2;
- break;
- case 条件3:命令3;
- break;
- defaut:命令4
- }
- public class book {
- public static void main(String[] args)
- {
- int a=1;
- switch(a)
- {
- case 1:
- System.out.println("a=1");
- break;
- case 2:
- System.out.println("a=2");
- break;
- default:
- System.out.println("都不是诶");
- }
-
-
- }
- }
a=1
为什么是这个?
很好理解对吧?
关键字switch后面括号里的变量是需要判断的变量.
case 后面的是一个固定的常量,变量值对于固定常量的时候,执行冒号后的语句.break,跳出判断.
而default这表示除此之外的情况的处理.
我们在需要大量判断的时候,很明显,switch比if更加优越.
每一个case语句后面都更着一个break.什么意思?
我们来看看另一个程序
- public class book {
-
- public static void main(String[] args)
- {
- int a=1;
- switch(a)
- {
-
-
- case 1:
- System.out.println("a=1");
- case 2:
- System.out.println("a=2");
- break;
- default:
- System.out.println("都不是诶");
-
-
- }
- }
- }
a=1
a=2
有什么不对吗?
实际上在没有break进行终止的情况下,这个语句将会从判断对的地方开始,下面的全部执行.
如果我将里面的另一个break也去掉会发生什么?
- public class book {
-
- public static void main(String[] args)
- {
- int a=1;
- switch(a)
- {
-
-
- case 1:
- System.out.println("a=1");
- case 2:
- System.out.println("a=2");
- default:
- System.out.println("都不是诶");
-
-
- }
- }
- }
- a=1
- a=2
- 都不是诶
代码我就不发了,这时的输出是
a=2
都不是诶
发现问题了吗?在判断成功后中断语句,这就是break的作用.意义不明?我们再来看一个程序.我们可以用这个来判断.
- public class book {
-
- public static void main(String[] args)
- {
- int a=7;
- switch(a)
- {
-
-
- case 1:
- case 2:
- case 12:
- System.out.println("银白的冬天");
- break;
- case 3:
- case 4:
- case 5:
- System.out.println("翠绿的春天");
- break;
- case 6:
- case 7:
- case 8:
- System.out.println("蔚蓝的夏天");
- break;
- case 9:
- case 10:
- case 11:
- System.out.println("金黄的秋天");
- break;
- default:
- System.out.println("一年只有十二个月好吗!!!");
-
-
- }
- }
输出是
蔚蓝的夏天
怎么样~很不错是吧.
最后要注意的一点,default一定放在最后?当然不是,其实它可以放在任何位置.
完