Java学习:if…else数据分支

后端学习评论6.3K字数 1410阅读4分42秒阅读模式

1、顺序结构

按部就班一步一步执行的结构,如:main

 文章源自亦枫博客-https://yflad.cn/1992.html

2、分支结构

单分支,双分支文章源自亦枫博客-https://yflad.cn/1992.html

if...else....:哪个分支的布尔表达式为ture时,就执行哪个分支中的内容,如果不满足继续执行else中的语句块。文章源自亦枫博客-https://yflad.cn/1992.html

单分支:文章源自亦枫博客-https://yflad.cn/1992.html

if(布尔表达式){
    语句块1;
}

 文章源自亦枫博客-https://yflad.cn/1992.html

if(布尔表达式){

    语句块1;
}else{
    语句块2;
}

多分支文章源自亦枫博客-https://yflad.cn/1992.html

if(布尔表达式){
    语句块1;
}else if{
    语句块2;
} else{
    语句块3;
}

 文章源自亦枫博客-https://yflad.cn/1992.html

小例子1:文章源自亦枫博客-https://yflad.cn/1992.html

int score = 55;
if (score >= 90 && score <= 100) {
    System.out.println("优秀");
} else if (score >= 80 && score < 90) {
    System.out.println("良好");
} else if (score >= 60 && score < 80) {
    System.out.println("及格");
} else if (score >= 0 && score < 60) {
    System.out.println("不及格");
} else {
    System.out.println("请输入正确的分数");
}

 文章源自亦枫博客-https://yflad.cn/1992.html

小例子2:文章源自亦枫博客-https://yflad.cn/1992.html

// 用if输出每一个月的天数 31t 1 3 5 7 8 10 12 30t 4 6 9 11
int m = 2; // month
int y = 2016; // year
if (m == 1 || m == 3 || m == 5 || m == 7 || m == 8 || m == 10 || m == 12) {
    System.out.println(m + "月是31天");
} else if (m == 4 || m == 6 || m == 9 || m == 11) {
    System.out.println(m + "月是30天");
} else if (m == 2) {
    // 闰年2月29天,平年28天。判断方法:年份能被4整除 且不能被100整除,或能够被400整除是 闰年
    if (y % 4 == 0 && y % 100 != 0 || y % 400 == 0) {
        System.out.println(m + "月是29天");
    } else {
        System.out.println(m + "月是28天");
    }
} else {
    System.out.println("请输入1~12");
}

 文章源自亦枫博客-https://yflad.cn/1992.html

小例子3:文章源自亦枫博客-https://yflad.cn/1992.html

// 用if分支判断每个月的属于什么季节
int j = 3;
if (j >= 2 && j <= 4) {
    System.out.println(j + "是春季");
} else if (j >= 5 && j <= 7) {
    System.out.println(j + "是夏季");
} else if (j >= 8 && j <= 10) {
    System.out.println(j + "是秋季");
} else if (j >= 11 && j <= 12 || j == 1) {
    System.out.println(j + "是冬季");
} else {
    System.out.println("请输入正确的月份");
}

// int j = 3;
if (j == 2 || j == 3 || j == 4) {
    System.out.println(j + "月份属于春季");
} else if (j == 5 || j == 6 || j == 7) {
    System.out.println(j + "月份属于夏季");
} else if (j == 8 || j == 9 || j == 10) {
    System.out.println(j + "月份属于秋季");
} else if (j == 11 || j == 12 || j == 1) {
    System.out.println(j + "月份属于冬季");
} else {
    System.out.println("请输入正确的月份");
}
文章源自亦枫博客-https://yflad.cn/1992.html文章源自亦枫博客-https://yflad.cn/1992.html
继续阅读
扫扫关注公众号
weinxin
我的微信
扫扫体验小程序
weinxin
我的公众号
亦枫
  • 本文由 发表于 2018年12月3日 19:32:06
评论  0  访客  0
匿名

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定