Java基础--->08.判断语句(if、else if、switch、while、do while)。
来源:互联网 发布:串口 数据帧 stm32 编辑:程序博客网 时间:2024/06/12 01:38
一、if---->相当于做判断题的语句。
int i = 0;//我们要判断i的值是不是等于0if(i == 0) {//如果i == 0的话,返回boolean类型,值为true,就走{}内 System.out.println("i的值确实为0!");}else{ //不为0,也就是false i = 0; //就把i的值赋值给0}System.out.println("i = " + i);
二、if、else if---->相当于做选择题的语句。
String str = "A";if("A".equals(str)){ System.out.println("恭喜,A是正确答案");}else if("B".equals(str)){ System.out.println("B不是真确答案");}else{ System.out.println("此题没有其它选项了");}
二、switch---->跟if else的区别。
switch用户支持short、byte、int、枚举、char注意:从jdk7.0开始,switch添加了对String的支持//使用switch编写简单的计算器char a = '+';switch(a){ case '+': System.out.println(2+2); break; //跳出switch case '-': System.out.println(2-2); break; default: System.out.println("不支持此运算符!"); //break; 可有可无,因为后面没有判断了}
switch的顺序是先执行case,最后执行default,我们也可以把default放上面,例如:
char a = '.';switch(a){ default: System.out.println("不支持此运算符!"); break;//如果此处不加break会继续下面的case判断,只到碰到break为止 case '+': System.out.println(2+2); break; case '-': System.out.println(2-2); break;}switch另外一种格式:
int i = 2;switch(i){ case 2: case 3: case 4: case 5: System.out.println("没错,2月-5月就是春天"); break; default: System.out.println("此程序只支持春天!");}
if和switch的选择:
如果判断的具体数值不多,而是符合byte、short、int、char这四种类型。
虽然两个语句都可以使用,建议使用switch语句,因为效率稍高。
PS:本人测试过1W跟100W数据,if明显高于switch,也可能是JDK7.0加入的新特性问题。
注意:对于区间判断,对结果为boolean类型的,if使用更广泛。
二、switch---->跟if else的区别。
while(boolean表达式){ //循环体}do{ //循环体}while(boolean表达式);区别:do while不管条件满不满足,都会执行一次。。。
- Java基础--->08.判断语句(if、else if、switch、while、do while)。
- JS:1.2控制语句(if,if else,for,switch,while,do while)
- PHP 结构控制 if else / switch / while / do while
- Swift第三课 分支语句 if else for forin switch while do-while
- c# 运算符 判断语句if-else、循环语句while ,do -while
- 循环语句if(){}else{}、if(){}else if(){}...else{}、do{}while()、for(){}、with(){}break/continue语句
- 控制流程语句if、switch、while、do-while、for
- 循环控制语句for while do-while if switch
- c++学习 day2 循环学习(while do while for) 分支学习(if ; if else; if else if; switch的应用 )
- java(4)------流程控制语句(if,switch,for,while,do-while)
- if判断语句 循环体for(){} while (){} do {}while();
- 选择 | 循环 | 语句(if,if……else,switch,while,for)的理解和使用
- Java语言基础(程序流程控制-if、switch、for、while、do while、break、continue)
- 分支语句 循环语句 if,switch,do,while,for分析
- java程序流程控制,if语句,switch语句,while语句,do while语句,for 语句,break关键字,continue关键字
- switch/while/if条件判断
- 3、C语言流程控制 if...else、switch、for、while、do while
- 求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。Java实现
- Scala开发入门指南
- windows xp 驱动开发(三)DDK与WDK WDM的区别
- 动态表单及动态建表实现原理
- Denoising Autoencoders (dA)
- Q格式
- Java基础--->08.判断语句(if、else if、switch、while、do while)。
- 设计模式读书笔记-----适配器模式
- Webkit 模块
- hdu1002
- having子句(重点)
- [转]《软件架构设计》学习笔记&摘录(四)
- 整理博客
- org.hibernate.QueryException: Expected positional parameter count: 2, actual parameters: [] [from Us
- Doctrine Annotations