/**PageBeginHtml Block Begin **/ /***自定义返回顶部小火箭***/ /*生成博客目录的JS 开始*/ /*生成博客目录的JS 结束*/

BlockTest

package com.alanliu.Java8BasicCodeStuding.Java8BasciCode.Unit2.Point5CodeBlock;

/*
 * 
 * 
   Demonstrate a block of code.

   Call this file "BlockTest.java"
*/
class BlockTest {
    public static void main(String args[]) {
        int x, y;

        y = 20;

        // the target of this loop is a block

        /**
         * Java允许将两条或多条语句分组到代码块中。代码块是通过在开花括号和闭花括号之间
         * 包装语句定义的。代码块一旦创建,它就变成了一个逻辑单元,可以用于能够使用单条语句的任何地方。
         * 例如,可以将代码块作为if和 for语句的目标。分析下面的if语句:
         * if(x<y){ll begin a block
         *   X= y;
         *   Y=0;
         *  } //end of block
         *  在此,如果x小于y,将执行代码块中的两条语句。
         *  因此,代码块中的两条语句一个逻辑单元,并且不能只执行一条语句而不执行另外一条语句。
         *  这里的关键点是,无论何时,当需要在逻辑上链接两条或更多条语句时,就可以通过创建一个代码块来实现。
         *  下面分析另外一个例子。下面的程序使用代码块作为for循环的目标:
         */
        for (x = 0; x < 10; x++) {
            System.out.println("This is x: " + x);
            System.out.println("This is y: " + y);
            y = y - 2;
        }
        /**
         *   由这个程序生成的输出如下所示:
         *      This is x: 0
                This is y: 20
                This is x: 1
                This is y: 18
                This is x: 2
                This is y: 16
                This is x: 3
                This is y: 14
                This is x: 4
                This is y: 12
                This is x: 5
                This is y: 10
                This is x: 6
                This is y: 8
                This is x: 7
                This is y: 6
                This is x: 8
                This is y: 4
                This is x: 9
                This is y: 2
               在这个例子中,for循环的目标是代码块,而不仅仅是一条语句。因此,每次迭代循环时,代码块中的3条语句都会被执行。上面程序的输出当然可以验证这一事实。
               在本书的后面将会看到,代码块还具有其他属性和用途。然而,它们存在的主要原因是创建逻辑上不可分割的代码单元。
         *   
         */
    }
}

 

posted @ 2022-02-17 21:43  一品堂.技术学习笔记  阅读(37)  评论(0编辑  收藏  举报