Java中的循环 方法

目录

循环

while

    初始化
    while(循环条件){
        循环体
        迭代
    }
    初始化
    while(循环条件, 迭代){
        循环体
    }

  public static void main(String[] args){
        //初始化
        byte b = 5;
        byte c = 0;
        //循环条件
        while( b != 0){
            //循环体
            c += 10;
            //迭代部分
            b--;
        }
        System.out.println((char)c);
        System.out.println(b);

    }

do while

注: 无论循环条件是真是假, 都必须执行一次

        初始化
        do {
            循环体
        } while(循环条件, 迭代);

for循环

    for(初始化; 条件; 迭代){
        循环体
    }

注: for循环的条件部分不写, 默认为true
优势: 对变量的生命周期有控制, 即初始化的变量只能在for循环体内部使用

break: 跳出指定的循环, 如没有指定则跳出当前循环
continue: 跳出指定本次循环, 如没有指定则跳出当前本次循环

案例

查找100以内的素数

//判断素数
public class Demo03{
    public static void main(String[] args){
        //总数
        int sum = 0;
        int count = 0;
        _L:
        //是否为素数的判定条件
        for(int i = 2; i <= 100; i++){
            //boolean isPrime = true;
            for(int j = 2; j <= Math.sqrt(i); j++){
                count++;
                if(i % j == 0){
                    //isPrime = false;
                    continue _L;//终止外层的本次循环
                }
            }
            sum++;
            //if(isPrime){
            //  sum++;
            //  System.out.print(i + " ");
            //}
        }
        System.out.println("\n100以内素数的总数为: " + sum);
        System.out.println("count=" + count);

    }
}

注意优化的部分: 去掉注释掉的boolean标记, 该用continue终止外层本次循环

方法

组成:

[注解] [修饰符] 返回值类型[泛型定义] 方法名(参数列表) [throws异常声明] 方法体

可以修饰方法的修饰符:

  • abstract
  • final
  • native
  • private, protected, public
  • static
  • strictfp
  • synchronized

静态方法不能被重写

传递:

    //值传递, 不会改变外面的值
    private static int add(int i, int j){
        return i + j;
    }
    //引用传递, 会改变外面的值
    private static void swap(int[] i, int[] j){
        int temp = i[0];
        i[0] = j[0];
        j[0] = temp;
    }

递归:

注: 跟循环一样, 一定会有一个出口

Fibonacci数列

递归方法


private static int fibonacci(int num){
        //跳出递归的条件
        if(num == 1 || num == 2){
            return 1;
        }else{
            return fibonacci(num - 2 ) + fibonacci(num - 1);
        }
    }

非递归方法

        int num1 = 1;
        int num2 = 1;

        for(int k = 3; k <= 7; k++){
            int temp = num1 + num2;
            num1 = num2;
            num2 = temp;
        }
        System.out.println(num2);

注: 能用循环的地方就不要使用递归

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值