流程控制、 迴圈語句
阿新 • • 發佈:2020-12-10
流程控制
- 順序結構
package com.kkb.hgd;
/*
順序結構
*/
public class Demo01 {
public static void main(String[] args) {
System.out.println(1);
System.out.println(2);
System.out.println(3);
}
}
- IF語句
package com.kkb.hgd; /* 分支結構:IF */ public class IfDemo01 { public static void main(String[] args) { System.out.println("開始"); // 定義兩個變數 int a=30; int b=20; if (a>b){ System.out.println(a+"大於"+b); } System.out.println("結束"); } }
package com.kkb.hgd; public class IfDemo03 { public static void main(String[] args) { // 定義兩個變數 a b int a=100; int b=200; if (a>b){ System.out.println(a+"大於"+b); }else { System.out.println(a+"小於"+b); } } }
package com.kkb.hgd; import java.util.Scanner; /* 需求: 隨機輸入學生的成績判斷學生的是否合格、優秀、良好 */ public class IfDemo04 { public static void main(String[] args) { Scanner scanner=new Scanner(System.in); System.out.println("請您輸入下成績:"); int score = scanner.nextInt(); if (score>=85){ System.out.println("小明成績優秀"); }else if (score>=75){ System.out.println("小明成績中等"); }else if(score>=60){ System.out.println("小明成績及格"); }else { System.out.println("小明成績不及格"); } } }
迴圈語句
- For語句格式
- For語句引用
package com.kkb.hgd;
/*
需求:列印10遍hello
*/
public class ForDemo01 {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.println("hello---"+i);
}
}
}
package com.kkb.hgd;
/*
需求: 在控制檯輸出1-5和5-1的資料
*/
public class ForDemo02 {
public static void main(String[] args) {
// 輸出1-5
for (int i = 1; i < 5; i++) {
System.out.println(i);
}
System.out.println("--------------------");
for (int i = 5; i >=1 ; i--) {
System.out.println(i);
}
}
}
package com.kkb.hgd;
/*
需求:求1-5之間的資料和,並把求和結果在控制檯輸出
*/
public class ForDemo03 {
public static void main(String[] args) {
int sum=0;
for (int i = 1; i <= 5 ; i++) {
sum+=i;
}
System.out.println("sum = " + sum);
}
}
package com.kkb.hgd;
/*
需求:求1-100之間的偶數和,並把求和結果在控制檯輸出
*/
public class ForDemo04 {
public static void main(String[] args) {
int sum=0;
for (int i = 1; i <= 100; i++) {
if (i % 2==0){
System.out.println(i);
sum+=i;
}
}
System.out.println("sum = " + sum);
}
}
package com.kkb.hgd;
/*
需求:使用巢狀迴圈,列印2021年至2023年月份,格式:xxxx年x月
*/
public class ForDemo05 {
public static void main(String[] args) {
for (int i = 2021; i < 2024; i++) {
System.out.println("-------------------------");
for (int j = 1; j <=12 ; j++) {
System.out.println(i+"年"+j+"月");
}
}
}
}