• Java终止循环体


        编写程序,是先创建一个字符串数组,在使用foreach语句遍历时,如果发现数组中包含字符串“老鹰”则立刻中断循环。再创建一个整数类型的二维数组,使用双层foreach语句循环遍历,当发现第一个小于60的数组元素,则立刻中断整个双层循环,而不是内层循环。

    public class Foreach {
        public static void main(String[] args){
        	System.out.println("
    -------------中断单层循环的例子-------------");
            // 创建数组
            String[] array = new String[] { "白鹭", "丹顶鹤", "黄鹂", "鹦鹉", "乌鸦", "喜鹊",
                    "老鹰", "布谷鸟", "老鹰", "灰纹鸟", "老鹰", "百灵鸟" };
            System.out.println("在你发现第一只老鹰之前,告诉我都有什么鸟。");
            for (String string : array) {							// foreach遍历数组
                if (string.equals("老鹰"))						// 如果遇到老鹰
                    break;// 中断循环
                System.out.print("有:" + string+"        ");		// 否则输出数组元素
            }
            System.out.println("
    -------------中断双层循环的例子-------------");
            // 创建成绩数组
            int[][] myScores = new int[][] { { 67, 78, 63, 22, 66 }, { 55, 68, 78, 95, 44 }, { 95, 97, 92, 93, 81 } };
            System.out.println("宝宝这次考试成绩:
    数学	语文	英语	美术	历史");
            No1: for (int[] is : myScores) {						// 遍历成绩表格
                for (int i : is) {
                    System.out.print(i + "	");					// 输出成绩
                    if (i < 60) {								// 如果中途遇到不及格的,立刻中断所有输出
                        System.out.println("
    等等," + i + "分的是什么?这个为什么不及格?");
                        break No1;
                    }
                }
                System.out.println();
            }
        }
    }
    

    效果如图所示:

  • 相关阅读:
    python
    基于vue的npm发包
    div实现水平垂直居中
    element-ui中表格添加fixed定位列后 出现表格错位现象
    解决github经常无法访问的问题
    快排算法C语言实现
    ubuntu下qt运行时/usr/bin/ld: cannot find -lGL
    llinux装完qt 启动qtcreator报错
    LINUX权限-bash: ./startup.sh: Permission denied
    In short, don’t use a pointer to a string literal if you plan to alter the string.
  • 原文地址:https://www.cnblogs.com/cysolo/p/3549862.html
Copyright © 2020-2023  润新知