zoukankan      html  css  js  c++  java
  • Java入门(五):控制流程

    在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学习电子书”,即可获得12本Java学习相关的电子书资源,如果经济能力允许,还请支持图书作者的纸质正版书籍,创作不易。

  • 相关阅读:
    最小生成树之prim算法
    洛谷P1443 马的遍历【BFS】
    (四)学习CSS之position、bottom、left、right和top属性
    (三)学习CSS之opacity 属性
    (二)学习CSS之cursor属性
    (一)学习CSS之z-index属性
    (八)学习MVC之三级联动
    (七)学习MVC之CodeFirst迁移更新数据库
    (六)学习MVC之标签a提交页面
    (四)学习MVC之修改个人资料和身份验证登陆
  • 原文地址:https://www.cnblogs.com/xiaochuan94/p/8391592.html
Copyright © 2011-2022 走看看