for循环语句

来源:互联网 发布:dota2淘宝怎么买饰品 编辑:程序博客网 时间:2024/03/28 20:41

        一、for循环语句的结构:

        for (表达式 1 ;表达式 2 ;表达式 3) { 
                若干语句
        }
        二、for循环语句执行过程的认识:
        初次循环先执行表达式1,再执行表达式2,在表达式2为true的前提下执行“若干语句”,再执行表达式3,再执行表达式2,在表达式2为true的前提下执行“若干语句”,再执行表达式3……依次的执行下去,直到表达式3的值不能使表达式2为true时,for循环结束。
        三、其它:
                 ①、将for循环设为死循环最简单的方法为for (;;) { 
                                若干语句
                        }
                ②、表达式 2为boolean类型,所以下面代码会在编译时出错:
                        for (System.out.println("1");System.out.println("2");System.out.println("3")){
                                System.out.println("4");
                        }
                ④、注意下面的代码没有错误:控制台输出:1434343
                        int i=0;
                        for (System.out.print("1");3>i;System.out.print("3"),i++){
                                System.out.print("4");
                        }
                        但是上面的代码这样写为什么在编译时就会出错呢
                        for (int i=0,System.out.print("1");3>i;System.out.print("3"),i++){
                                System.out.print("4");
                         }
                        究其原因弄清逗号的作用:例如定义两个int类型的变量a和b,我们可以这样做:int a,b,那么这表示a和b变量的类型是相同的,上面for循环之所以出现编译性错误主要是这样做意味着“System.out.print("1")”也成int类型了,而现实是“System.out.print("1")”并不是int类型。
                        如果将上面的代码改成下面的则可以:
                        int i;
                        for (i=0,System.out.print("1");3>i;System.out.print("3
"),i++){
                                System.out.print("4");
                       }
                ⑤、for循环这种形式:
                       public static void main(String[] args){
                                f:for (int i = 0; i < 3; i++){
                                        if (i==1) {
                                                break f;
                                        }
                                        System.out.println("李四");
                                }
                        }
                        说明:上面循环只输出一次“李四”字符串。
原创粉丝点击