JAVA--程序逻辑控制

程序逻辑结构

1.顺序结构

2.选择结构

  • if语句和switch语句
  • if语句可以判断条件语句(布尔表达式语句);
  • switch语句只能判断内容;
  1. if语句
if (score >= 60) 
    System.out.println("成绩及格");
//只有一个if语句,可以去掉{};
  1. if…else
if (sorce >= 60) {
    System.out.println("成绩及格");
} else {
    System.out.println("成绩不及格");
}
  1. if…else if…else
if (score >= 90) {
            System.out.println("成绩优秀");
        } else if (score >= 80){
            System.out.println("成绩良好");
        } else if (score >= 60) {
            System.out.println("成绩及格");
        } else {
            System.out.println("成绩不及格");
        }

4.switch语句

int a = new Scanner(System.in).nextInt();
switch (a) {
    case 1: {
         System.out.println("1");
         break;
    }
    case 2: {
         System.out.println("2");
         break;
    }
}

3.循环结构

  1. while(限定条件)先判定,后计算
int a = new Scanner(System.in).nextInt();
        int sum = 0;
        while (a != -1) {
        //当a != -1继续循环;
            sum += a;
            a = new Scanner(System.in).nextInt();
        }
        System.out.println(":" + sum);
  1. do…while(限定条件)先计算,后判定
 int a = new Scanner(System.in).nextInt();
        int sum = 0;
        do {
            sum += a;
            a = new Scanner(System.in).nextInt();
        } while (a != -1);
        System.out.println(sum);
  1. for循环
for (int x = 1; x <= 9; x++) {
//控制横轴
    for (int y = 1; y <= x; y++) {
    //控制纵轴
        System.out.print(x + "*" + y + "=" + (x * Y) + "\t");
        //输出九九乘法表;
    }
    System.out.println();
}

foreach循环

  • 增强for循环 --> 底层迭代器
  • 在遍历增强for循环时,修改数据,会出现并发修改异常.
for ( Object o(从array中取出的数据,指定类型, 定义变量) : array (被遍历数组)) {
    System.out.println(o);
}

循环控制

  • break --> 退出整个循环
  • continue --> 退出本次循环

猜你喜欢

转载自blog.csdn.net/weixin_40107544/article/details/88615750