循环


一、if判断


// 格式1:
int age = 27;
if (age > 18) {
System.out.println("上网浏览信息~ Github.com 全球最大的同性交友网址");
}


// 格式2:
if (age < 18) {
System.out.println("继续上网浏览信息~ Github.com 全球最大的同性交友网址");
} else {
System.out.println("好好读书,天天吃烤肉");
}

/*格式3:
if (boolean结果表达式) {}
else if (boolean结果表达式) {}
else if (boolean结果表达式) {}
..
else {}*/
int height = 100;
if (height >= 60 && height <= 100) {
System.out.println("成仙");
} else if (height >= 50 && height < 60) {
System.out.println("抱孙子");
}
else {
System.out.println("输入有误");
}

二、switch

// switch()中的值:char,byte ,short, int,String ,enum
// switch 什么时候结束,遇到break,遇到}
// 如果把case中break去掉,break穿透
// switch 只能做等值匹配, 如果做等值,比if性能高。
char c = 'b';
switch (c) {
case 'a':
System.out.println("char1 :" + c);
//break;
case 'b':
System.out.println("char2 :" + c);
//break;
case 'c':
System.out.println("char3 :" + c);
break;
default:
System.out.println("default :");
}
三、循环
  1. for循环
    /*1、格式for(初始化语句 1 ;条件判断语句 2 ;循环体执行之后的语句 4) {循环体 3 ;}*/
    for (int i = 1; i <= 10; i++) {
    System.out.println(i);
    }
    //1到10的累加求和
    int sum = 0;
    for (int i = 0; i <= 10; i++) {
    sum += i;
    }
    System.out.println(sum);
    //双层for循环
    for (int i = 1; i <= 4; i++) { //控制行 //控制行
    for (int j = 1; j <= 5; j++) { //控制列
    System.out.print("-");
    }
    System.out.println();
    }
    // 遍历一维数组
    int[] arr = {2, 3, 4, 1, 5};
    for(int i=0;i<arr.length;i++) {
    System.out.println(arr[i]);
    }
    //倒着遍历数组
    //增强for循环,简化遍历数组和集合,对象
    //缺点:无法直接获取索引,只能从头挨个遍历到尾
    for (int element : arr) {
    System.out.println(element);
    }
    //遍历二维数组
    int[][] arr = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}};
    for (int i = 0; i < arr.length; i++) {
    //System.out.println(i);
    //System.out.println(arr[i][0]);
    //System.out.println(arr[i][1]);
    for(int j=0;j<arr[i].length;j++) {
    System.out.println(arr[i][j]);
    }
    }
    // 增强for循环,遍历二维数组
    int[][] arr2 = {{12,3,2},{3,1,2},{0,9}};
    for(int[] subArr : arr2) {
    for(int element : subArr) {
    System.out.println(element);
    }
    System.out.println();
    }
  2. While循环
    int i = 1;
    //如果你能直接拿到循环判断条件
    while (i <= 10) {
    System.out.println(i);
    i++;
    }
    System.out.println(i);
  3. DoWhile循环
    int i = 11;
    //无论循环条件
    // 是否成立,至少会执行一次循环体。
    do {
    System.out.println(i);
    i++;
    } while (i <= 10);
  4. 控制循环
    //continue跳过本次循环,继续执行下面的循环
    for (int i = 0; i < 10; i++) {
    if (i == 3) {
    continue;//跳过本次循环,0-1-2-4-5-6-7-8-9
    }
    System.out.println(i);

    }
    //break终止循环
    for (int i = 0; i < 10; i++) {
    if (i == 3) {
    break;////终止循环,0-1-2
    }
    System.out.println(i);

    }




posted @ 2022-09-10 15:03  袁丫头  阅读(81)  评论(0)    收藏  举报