Java入门(五):控制流程

Wesley13
• 阅读 547

在Java中,使用条件语句和循环结构确定控制流程,在本文中,主要包括块作用域、条件语句、循环结构、中断循环这四部分。

一、块作用域

块,也叫复合语句,是指由一对大括号括起来的若干条Java语句。块决定了变量的作用域。一个块可以嵌套多个块。

二、条件语句

如果判断超过三层,建议拆分开来写,这样更加清晰。

package javalearningday04;

/**
 * 条件语句
 * @author 小川94
 * @date 2018年1月31日
 */
public class IfElseDemo {

    public static void main(String[] args) {
        testMethod(78);
    }
    
    /**
     * 判断成绩
     */
    public static void testMethod(int score) {
        if (score < 0) {
            System.out.println("请传入正确的分数!");
        } else {
            if (score >= 90 && score <= 100) {
                System.out.println("成绩优秀");
            } else if (score >= 80) {
                System.out.println("成绩良好");
            } else if (score >= 70) {
                System.out.println("成绩一般");
            } else if (score >= 60) {
                System.out.println("成绩及格");
            } else {
                System.out.println("不及格");
            }
        }
    }
}

三、循环结构

3.1 for循环

package javalearningday04;

/**
 * for循环的用法
 * @author 小川94
 * @date 2018年1月31日
 */
public class ForDemo {
    
    public static void main(String[] args) {
        testMethod();
        testMethod2();
    }
    
    /**
     * 计算1,2,3...,100的和
     */
    public static void testMethod() {
        int sum = 0;
        for (int i=1; i<101; i++) {
            sum += i;
        }
        System.out.println(sum); //sum = 5050
    }
    
    public static void testMethod2() {
        String[] strArray = {"小明","小马","小王"};
        // foreach循环遍历
        for (String str : strArray) {
            System.out.println(str); // 依次打印 小明  小马  小王
        }
        // 两种写法的输出结果都是一样的
        for (int i=0; i<strArray.length; i++) {
            System.out.println(strArray[i]); // 依次打印 小明  小马  小王
        }
    }
    
}

3.2 do{...}while()循环

先执行,再判断。无论while中的条件是否成立,都会执行一次循环体。

package javalearningday04;

/**
 * do{}while();的用法
 * @author 小川94
 * @date 2018年1月31日
 */
public class DoWhileDemo {

    public static void main(String[] args) {
        testMethod();
        testMethod2();
    }
    
    /**
     * 计算1,2,3...,100的和
     * 先执行,后判断
     */
    public static void testMethod() {
        int i = 1;
        int sum = 0;
        do{
            sum += i;
            i++;
        }while(i<101);
        System.out.println(sum); // sum = 5050
        System.out.println(i); // i = 101
    }
    
    /**
     * do{}while();的循环结构,至少会执行一次循环体
     * 在while中的条件不成立时,已经执行了一次循环体
     */
    public static void testMethod2() {
        int i = 1;
        int sum = 0;
        do{
            sum += i;
            i++;
        }while(i<1);
        System.out.println(sum); // sum = 1
        System.out.println(i); // i = 2
    }
}

3.3 while(){...}循环

先判断,再执行。只有条件成立,才会进入循环体。

package javalearningday04;

/**
 * while(){}的用法
 * @author 小川94
 * @date 2018年1月31日
 */
public class WhileDemo {

    public static void main(String[] args) {
        testMethod();
        testMethod2();
    }
    
    /**
     * 计算1,2,3...,100的和
     * 先判断,后执行
     */
    public static void testMethod() {
        int i = 1;
        int sum = 0;
        while( i<101 ){
            sum += i;
            i++;
        }
        System.out.println(sum); // sum = 5050
        System.out.println(i); // i = 101
    }
    
    /**
     * 只有while()中的条件成立时,才会执行循环体
     * 如果while()中的条件永久为true,则会进入死循环,对程序会造成非常严重的后果,
     * 开发中需要严格判断循环条件!避免出现死循环
     */
    public static void testMethod2() {
        int i = 1;
        int sum = 0;
        while( i<1 ){
            sum += i;
            i++;
        }
        System.out.println(sum); // sum = 0
        System.out.println(i); // i = 1
    }
    
}

3.4 独特的switch{}

package javalearningday04;

/**
 * switch{}的用法
 * @author 小川94
 * @date 2018年1月31日
 */
public class SwitchCaseDemo {

    public static void main(String[] args) {
        testMethodWithInt(3);
        testMethodWithByte((byte)3);
        testMethodWithChar((char)3);
        testMethodWithShort((short)3);
        testMethodWithString("MONDAY");
        testMethodWithEnum(SIZE.MEDIUM);
        testSwitchWithoutBreak("MONDAY");
    }
    
    // 支持int
    public static void testMethodWithInt(int num) {
        switch (num) {
            case 0:
                System.out.println("num等于0");
                break;
            default:
                System.out.println(num);
                break;
        }
    }
    
    // 支持byte
    public static void testMethodWithByte(byte num) {
        switch (num) {
            case 0:
                System.out.println("num等于0");
                break;
            default:
                System.out.println(num);
                break;
        }
    }
    
    // 支持char
    public static void testMethodWithChar(char num) {
        switch (num) {
            case 0:
                System.out.println("num等于0");
                break;
            default:
                System.out.println(num);
                break;
        }
    }
    
    // 支持short
    public static void testMethodWithShort(short num) {
        switch (num) {
            case 0:
                System.out.println("num等于0");
                break;
            default:
                System.out.println(num);
                break;
        }
    }
    
    // 支持字符串
    public static void testMethodWithString(String str) {
        switch (str) {
            case "MONDAY":
                System.out.println("是星期一");
                break;
            default:
                System.out.println(str);
                break;
        }
    }
    
    public enum SIZE{
        // 小号
        SMALL,
        // 中号
        MEDIUM,
        // 大号
        LARGE;
    }
    
    public SIZE size;
    
    public SwitchCaseDemo(SIZE size) {
        this.size = size;
    }
    // 支持枚举类型
    public static void testMethodWithEnum(SIZE size) {
        switch (size) {
            case SMALL:
                System.out.println("是小号");
                break;
            case MEDIUM:
                System.out.println("是中号");
                break;
            case LARGE:
                System.out.println("是大号");
                break;
            default:
                System.out.println("没有其他号了");
                break;
        }
    }
    
    // 不写break语句,则每种情况都会执行
    public static void testSwitchWithoutBreak(String str) {
        switch (str) {
            case "MONDAY":
                System.out.println("吃包子");
            case "SUNDAY":
                System.out.println("吃面条");
            default:
                System.out.println("喝粥");
        }
    }
    
    // 不支持long类型的数据
    /*public static void testMethodWithLong(long num) {
        switch (num) {
            case 0:
                System.out.println("num等于0");
                break;
            default:
                System.out.println(num);
                break;
        }
    }*/
    
    // 不支持double类型的数据
    /*public static void testMethodWithDouble(double num) {
        switch (num) {
            case 0:
                System.out.println("num等于0");
                break;
            default:
                System.out.println(num);
                break;
        }
    }*/
}

四、中断循环

中断循环需要用到两个关键字,一是continue,另一个是break。

continue是指将其后面的执行语句跳过,进入下一次新的循环,整个循环结构是还在运行的,没有终止。

break是指结束掉整个循环结构,开始执行整个循环结构的后面的代码。

package javalearningday04;

/**
 * continue、break的用法
 * @author 小川94
 * @date 2018年1月31日
 */
public class ContinueBreakDemo {

    public static void main(String[] args) {
        testContinue();
        testBreak();
    }
    
    /**
     * 求数组中正数的和
     * continue:在执行完continue语句后,其后的代码都不再执行,
     *          结束本次循环,进入下一次循环,整个循环结构还在继续执行
     */
    public static void testContinue() {
        int[] arr = {1,2,3,4,-5,6};
        int sum = 0;
        for(int i=0; i<arr.length; i++){
            if (arr[i]<0) { //过滤数组中的负数
                continue; 
            } else {
                sum += arr[i];
            }
        }
        // 跳过-5,计算1+2+3+4+6的和
        System.out.println(sum); // sum = 16
    }
    
    /**
     * break:在执行完break语句后,其后的代码都不再执行,
     *       结束整个循环结构,
     */
    public static void testBreak() {
        int[] arr = {1,2,3,4,-5,6};
        int sum = 0;
        for(int i=0; i<arr.length; i++){
            if (arr[i]<0) { 
                break; // 与上面的代码一样,只是将continue换成了break
            } else {
                sum += arr[i];
            }
        }
        // 只会计算1+2+3+4的和
        System.out.println(sum); // sum = 10
    }
}

上面的代码都上传至了GitHub,地址是https://github.com/XiaoChuan94/javalearning/tree/master/javalearningday04,有需要的可以去下载观看,如果喜欢就给个star吧!如有不足,欢迎下方留言交流。

文章首发于我的个人公众号:悦乐书****。喜欢分享一路上听过的歌,看过的电影,读过的书,敲过的代码,深夜的沉思。期待你的关注!

Java入门(五):控制流程

公众号后台输入关键字“Java学习电子书”,即可获得12本Java学习相关的电子书资源,如果经济能力允许,还请支持图书作者的纸质正版书籍,创作不易。

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Karen110 Karen110
2年前
一篇文章带你了解JavaScript switch
Switch是与if...else...相同的条件语句,不同之处在于switch语句允许根据值列表测试变量是否相等。switch语句用于根据不同的条件执行不同的操作。一、Switch语句使用switch语句选择要执行的多个代码块中的一个。1\.语法switch(expression)casen:codeblock
Karen110 Karen110
2年前
一篇文章带你了解JavaScript While 循环
循环可以执行一个代码块,只要指定条件为真,循环就可以执行代码块。一、While循环while只要指定条件的值为真,循环就会执行指定语句。while循环的语法while(condition)statement//只要条件为真,就执行代码例:项目JavaScriptwhile语句只要n小于5,就遍历一段代码:varn0;while(n<
Stella981 Stella981
2年前
Python3:sqlalchemy对mysql数据库操作,非sql语句
Python3:sqlalchemy对mysql数据库操作,非sql语句python3authorlizmdatetime2018020110:00:00coding:utf8'''
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Wesley13 Wesley13
2年前
Java05
Java05Java基础语法(四)循环结构循环结构(重复/迭代):根据条件重复执行部分语句1、while循环结构while(条件表达式){     循环体语句;}1)语法:a、while是关键字        b、“条件表达式”必须用括号括起来        c、“{}”表示循环的控制范围,若没有“{}”,whil
Wesley13 Wesley13
2年前
C语言二次系统学习3(分支循环、函数)
本次学习,主要针对语句和函数两部分进行学习。分支语句(if,switch)与循环语句(while,for,dowhile)switch语句中,在每个选择之后如果不进行break跳出,会执行下一个case,而且应注意default语句的使用,一般会放在{}代码块的后方dowhile语句中,会首先执行一次循环,再进行判定,所以使用相对较少。whi
Stella981 Stella981
2年前
Python—语法基础(8) 分支、循环结构
分支紧凑格式:<表达式1if<条件else<表达式2分支结构if<条件1:<语句块1elif<条件2:<语句块2……else:<语句块N异常处理try:
小万哥 小万哥
3个月前
深入解析 C 语言中的 for 循环、break 和 continue
C语言中的for循环当您确切地知道要循环执行代码块的次数时,可以使用for循环而不是while循环cfor(语句1;语句2;语句3)//要执行的代码块语句1在执行代码块之前执行(一次)。语句2定义执行代码块的条件。语句3在执行代码块后执行(每次)。下面的示
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这