程序设计基础(流程控制)
一、流程控制是什么?
解释:在一个程序执行的过程中,各条代码的执行顺序对程序的结果是有直接影响的,很多时候我们要通过控制代码的执行顺序来实现我们要完成的功能。
二、顺序控制语句
-按照代码执行的先后顺序。
代码如下(示例):
public class ControlDemo {
public static void main(String[] args) {
System.out.println("重庆");
System.out.println("工商");
System.out.println("大学");
System.out.println("派斯");
System.out.println("学院");
}
}
结果
三、if控制语句
-选择结构又叫分支结构,选择结构用于判断给定的条件,根据判断的结果判断条件,根据判断的结果来控制程序的执行流程。
public class ControlDemo {
public static void main(String[] args) {
int a = 5;
int b = 6;
if (a > b) {
System.out.println(a);
} else {
System.out.println(b);
}
}
}
结果
public class WeightLossProgramif {
public static void main(String[] args) {
System.out.println("请输入星期数");
Scanner s1 = new Scanner(System.in);
int w1 = s1.nextInt();
if (w1 < 1 || w1 > 7) {
System.out.println("输入有误!!");
} else if (w1 == 1) {
System.out.println("跑步");
} else if (w1 == 2) {
System.out.println("游泳");
} else if (w1 == 3) {
System.out.println("慢走");
} else if (w1 == 4) {
System.out.println("动感单车");
} else if (w1 == 5) {
System.out.println("拳击");
} else if (w1 == 6) {
System.out.println("爬山");
} else {
System.out.println("好好吃一顿!");
}
}
}
四、switch控制语句
public class WeightLossProgramswitch {
public static void main(String[] args) {
System.out.println("请输入星期数");
Scanner s1 = new Scanner(System.in);
int w1 = s1.nextInt();
if (w1 < 1 || w1 > 7) {
System.out.println("输入有误!!");
}
switch (w1) {
case 1:
System.out.println("跑步");
break;
case 2:
System.out.println("游泳");
break;
case 3:
System.out.println("慢走");
break;
case 4:
System.out.println("动感单车");
break;
case 5:
System.out.println("拳击");
break;
case 6:
System.out.println("爬山");
break;
case 7:
System.out.println("好好吃一顿");
break;
}
}
}
五、for循环结构
public class ControlDemo {
public static void main(String[] args) {
for (int i = 0;i < 10;i++){
System.out.println("i的数值是:"+i);
}
}
}
六、while循环结构
public class ControlDemo {
public static void main(String[] args) {
int i = 0;
while (i <10){
System.out.println("i的数值是:"+i);
i++;
}
}
}
七、do while循环结构
public class ControlDemo {
public static void main(String[] args) {
int i=1;
do {
System.out.println("i的数值是:"+i);
i++;
}while(i<=10);
}
}
注意事项
- Switch能实现的,if都能实现,但if能实现的,switch不一定能实现。
总结
- 了解了流程控制的基本原理。
- 掌握了流程执行的步骤。