Java初学者之流程控制
Java流程控制
顺序结构
public class SequenceDemo {
public static void main(String[] args) {
System.out.println("Hello1");
System.out.println("Hello2");
System.out.println("Hello3");
System.out.println("Hello4");
System.out.println("Hello5");
}
}
if 选择结构
public class IfDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入分数:");
int score = scanner.nextInt();
if (score>=60){
System.out.println("及格");
}else{
System.out.println("不及格");
}
scanner.close();
}
}
switch 选择结构
public class SwitchDemo {
public static void main(String[] args) {
char grade = 'D';
switch(grade){
case 'A':
System.out.println("优秀");
break;
case 'B':
System.out.println("良好");
break;
case 'C':
System.out.println("再接再厉");
break;
case 'D':
System.out.println("不及格");
break;
default:
System.out.println("未知等级");
}
}
}
while 和 do while 结构
public class WhileDemo01 {
public static void main(String[] args) {
//输出1~100
int i = 0;
while(i < 100){
i++;
System.out.println(i);
}
}
}
输出
1
2
3
4
...
100
public class DoWhileDemo01 {
public static void main(String[] args) {
//输出1~100
int i = 0;
do {
i++;
System.out.println(i);
}while(i < 100);
}
}
虽然输出结果是相同的,但是 while 和 do-while 还是有区别的,他们之间最大的区别就是,while只会当括号里面的条件成立才会进行循环,而 do-while 则是至少执行一次循环再来判断 while 是否成立从而进行下一次循环!
for 循环
for 循环的一般表达式为:
for (单次表达式; 条件表达式; 末尾循环体){
//中间循环体
}
public class ForDemo01 {
public static void main(String[] args) {
//练习1 : 计算0~100之间的奇数和与偶数和
int oddSum = 0; //奇数和
int evenSum = 0; //偶数和
for (int i = 0; i <= 100; i++) {
if (i%2!=0){
oddSum = oddSum + i;
}else{
evenSum = evenSum + i;
}
}
System.out.println("奇数的和为:" + oddSum);
System.out.println("偶数的和为:" + evenSum);
}
}
可以利用 for 循环来输出九九乘法表
public class ForDemo02 {
public static void main(String[] args) {
for (int i = 1; i < 10; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j + "*" + i + "=" + (i*j) + "\t");
}
System.out.println();
}
}
}
输出结果:
1×1=1
1×2=2 2×2=4
1×3=3 2×3=6 3×3=9
1×4=4 2×4=8 3×4=12 4×4=16
1×5=5 2×5=10 3×5=15 4×5=20 5×5=25
1×6=6 2×6=12 3×6=18 4×6=24 5×6=30 6×6=36
1×7=7 2×7=14 3×7=21 4×7=28 5×7=35 6×7=42 7×7=49
1×8=8 2×8=16 3×8=24 4×8=32 5×8=40 6×8=48 7×8=56 8×8=64
1×9=9 2×9=18 3×9=27 4×9=36 5×9=45 6×9=54 7×9=63 8×9=72 9×9=81
增强 for 循环(foreach循环)
通常的表达式为:
for(声明语句 : 表达式){
//代码
}
foreach 通常拿来做数组的遍历

浙公网安备 33010602011771号