【Java学习笔记】---Java流程控制

Java中流程控制主要有以下几种:

选择语句:

  1.if(condition)

    statement1;

    else statement2;

    >>statement1, statement2可以是单个语句(statement),也可以是程序块(block)。

    >>条件condition可以是任何返回布尔值的表达式。else子句是可选的。

  2. switch(expression) {

    case value1:

        ...//statement sequence

        breake;

    case value2:

        ...//statement sequence

        breake;

    default:

        //default statement

    }

  >> expression必须是byte, short, int或char类型(数据类型长度小于等于32位),在JDK5.0中可以是用枚举类型的。

  >>每个case语句后的值value必须是与表达式类型兼容的特定的一个常量(必须是常量,而不是变量)。重复的case值是不允许的。case语句只是起到一个标号作用,用来查找匹配的入口并从此处开始执行其后的语句。 

  eg:

package com.annie;

public class TestSwitch {
    public static void main(String args[]) {
        switch (2) {
        case 1:
            System.out.println("case 1");
        case 2:
            System.out.println("case 2");
        case 3:
            System.out.println("case 3");
        default:
            System.out.println("case default");

        }
    }
}

易错点:缺少break语句,case 2后所有的语句都会被执行。

 

 

循环

while语句:

while(condition)

{

// body of loop

...

}

do-while语句:

  do

  {

  // body of loop

  ...

  }while(condition)

do-while比while语句多执行一次。。。

for语句:

  for(initialization; condition; iteration) {

  // body

  ...

  }

>>在for循环内声明变量。

>>在for循环中使用逗号。

eg: 

for (int a = 1, b = 4; a < b; a++, b--) {
            System.out.println("a = " + a);
            System.out.println("b = " + b);
 }

>>可以用for语句遍历一个数组或集合中的所有元素。

eg:

 1 package com.annie;
 2 
 3 public class TestForEach {
 4     public static void main(String args[]) {
 5         int sum = 0;
 6         int a[] = new int[100];
 7         for (int i = 0; i < 100; i++) {
 8             a[i] = i;
 9         }
10 
11         // for-each语句的使用
12         for (int e : a)
13             sum = sum + e;
14         System.out.println("the sum is" + sum);
15     }
16 }

 

跳转语句:

1.break语句:

 >>使用break退出循环;

 >>把break当作goto的一种形式来用

2.continue语句:

  >>跳出本次循环,继续下一次循环

  >>continue带标号,类似于goto;

3.return语句

  >>return语句用来明确地从一个方法返回。

转载于:https://www.cnblogs.com/annieyu/p/3639401.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值