1 流程控制语句
1.1 什么是流程控制语句
1.2 流程控制语句的分类
2 顺序结构
3 分支结构
3.1 分支结构的分类
3.2 if语句的格式
class IfStruct1{
public static void main(String[] args) {
if(布尔表达式){
//语句体
}
}
}
class IfStruct2{
public static void main(String[] args) {
if(布尔表达式){
//语句体1
}else{
//语句体2
}
}
}
class IfStruct3{
public static void main(String[] args) {
if(布尔表达式1){
//语句体1
}else if(布尔表打死2){
//语句体2
}else{
//语句体3
}
}
}
3.3 执行流程
- 先计算比较表达式的值,看其返回值是true还是false。
- 如果是true,则执行语句体。
- 如果是false,则不执行语句体。
3.4 示例
package com.xuweiwei;
public class IfDemo {
public static void main(String[] args) {
int x = 0;
if(x ==0){
System.out.println("你好啊");
}
System.out.println("世界");
}
}
package com.xuweiwei;
public class IfDemo {
public static void main(String[] args) {
int x = 2;
if(x % 2 == 0){
System.out.println("是偶数");
}else{
System.out.println("是奇数");
}
}
}
package com.xuweiwei;
public class IfDemo {
public static void main(String[] args) {
char c = '男';
if (c == '男'){
System.out.println("你是男生");
}else if(c =='女'){
System.out.println("你是女生");
}else{
System.out.println("你的性别暂时不能识别");
}
}
}
package com.xuweiwei;
public class IfTest {
public static void main(String[] args) {
int a = 10;
int b = 20;
int c = 30;
if(a > b){
if(a > c){
System.out.println("a="+a+"最大");
}else{
System.out.println("c="+c+"最大");
}
}else{
if(b > c){
System.out.println("b="+b+"最大");
}else{
System.out.println("c="+c+"最大");
}
}
}
}
3.5 switch语句
switch(表达式){//表达式可以是byte short int char 枚举,JDK7新增了String
case 值1:
语句体1;
break;
case 值2:
语句体2;
break;
……
default:
语句体n;
break;
}
package com.xuweiwei;
public class IfTest {
public static void main(String[] args) {
String str = "a";
switch (str) {
case "a":
System.out.println("a");
break;
case "b":
System.out.println("b");
break;
default:
System.out.println("你好");
break;
}
}
}
package com.xuweiwei;
import java.util.Scanner;
public class IfTest {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("请输入1-7:");
int num = input.nextInt();
if (num < 0 || num > 7) {
System.out.println("抱歉,输入数字不合法");
} else {
switch (num) {
case 1:
System.out.println("星期一");
break;
case 2:
System.out.println("星期二");
break;
case 3:
System.out.println("星期三");
break;
case 4:
System.out.println("星期四");
break;
case 5:
System.out.println("星期五");
break;
case 6:
System.out.println("星期六");
break;
default:
System.out.println("星期天");
break;
}
}
}
}
- switch的注意事项
- ①case后面只能是常量,不能是变量,而且,多个case后面的值是不可以相同的。
- ②default是可以省略的,但是不建议。
- ③break也可以省略,但是可能会造成穿透现象。
- ④default语句不一定要在最后,但是建议在最后。
- ⑤switch语句的结束条件:1、遇到break语句就结束了 2、执行到switch的右大括号就结束了。
4 if和switch的区别
- if建议判断区间或范围
- switch建议判断固定值的时候使用