第四章笔记《Thinkinng in JAVA》

第四章 控制执行流程

4.1 true和false

4.2 if-else

4.3 迭代

while、do-while、for

4.4 Foreach语法

foreach 语法,表示不必创建int变量去访问项构成的序列进行计数,foreach 将自动产生每一项。

//: control/ForEachFloat.java
import java.util.*;

public class ForEachFloat {
  public static void main(String[] args) {
    Random rand = new Random(47);
    float f[] = new float[10];
    for(int i = 0; i < 10; i++)
      f[i] = rand.nextFloat();
    for(float x : f)
      System.out.println(x);
  }
} /* Output:
0.72711575
0.39982635
0.5309454
0.0534122
0.16020656
0.57799757
0.18847865
0.4170137
0.51660204
0.73734957
*///:~

for(float x : f)
定义一个float类型的变量x,继而将每一个f的元素赋值给x。

4.5 return

4.6 break和continue

  • break用于强行退出循环,不执行循环中剩余的语句
  • continue 则停止执行当前的迭代,然后退回循环起始处,开始下一次迭代。
//: control/BreakAndContinue.java
// Demonstrates break and continue keywords.
import static net.mindview.util.Range.*;

public class BreakAndContinue {
  public static void main(String[] args) {
    for(int i = 0; i < 100; i++) {
      if(i == 74) break; // Out of for loop
      if(i % 9 != 0) continue; // Next iteration
      System.out.print(i + " ");
    }
    System.out.println();
    // Using foreach:
    for(int i : range(100)) {
      if(i == 74) break; // Out of for loop
      if(i % 9 != 0) continue; // Next iteration
      System.out.print(i + " ");
    }
    System.out.println();
    int i = 0;
    // An "infinite loop":
    while(true) {
      i++;
      int j = i * 27;
      if(j == 1269) break; // Out of loop
      if(i % 10 != 0) continue; // Top of loop
      System.out.print(i + " ");
    }
  }
} /* Output:
0 9 18 27 36 45 54 63 72
0 9 18 27 36 45 54 63 72
10 20 30 40
*///:~

-标签,是后面跟有冒号的标识符,eg. label1:

label1:
outer-iteration {
    innner-iteration{
        //...
        break;//(1)
        //...
        continue;//(2)
        //...
        continue label1;//(3)
        //...
        break label1;//(4)
    }
}

在(3)中,continue label1 同时中断内部迭代以及外部迭代,直接转到 label1 处,随后继续迭代。在(4)中, break label1 也中断所有迭代,并回到label1 处,但并不重新进入迭代。

4.8 switch

switch ( ) {
case : ; break;
default: ;
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容