一、If語句。
1、語句格式:
第一種:
if(關係表達式) {
語句體
}
執行流程:
首先判斷關係表達式看其結果是true還是false
如果是true就執行語句體
如果是false就不執行語句體
public class test01 {
public static void main(String[] args) {
int a=10;
int b=20;
if(a==b) {
System.out.println(true);
}
}
}
第二種:
if語句第二種格式:
if(關係表達式) {
語句體1;
}else {
語句體2;
}
public class test01 {
public static void main(String[] args) {
int a=10;
int b=20;
if(a==b) {
System.out.println(true);
} else {
System.out.println(false);
}
}
}
第三種:
接第二種後繼續接
else {
語句體n+1;
}
首先判斷關係表達式1看其結果是true還是false
如果是true就執行語句體1
如果是false就繼續判斷關係表達式2看其結果是true還是false
如果是true就執行語句體2
如果是false就繼續判斷關係表達式…看其結果是true還是false
…
如果沒有任何關係表達式爲true,就執行語句體n+1
二、Switch語句
格式:
switch(表達式) {
case 值1:
語句體1;
break;
case 值2:
語句體2;
break;
…
default:
語句體n
break;
public static void main(String[] args) {
//創建鍵盤錄入對象
Scanner sc = new Scanner(System.in);
//接收數據
System.out.println("請輸入一個數字(1-7):");
int weekday = sc.nextInt();
//switch語句實現選擇
switch(weekday) {
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;
default:
System.out.println("你輸入的數字有誤");
break;
}
}
}
三、for 循環控制語句
格式:
for(初始化語句;判斷條件語句;控制條件語句) {
循環體語句;
}
public static void main(String[] args) {
for(int a=1;a<=10;a++) {
System.out.println("helloworld");
}
}
利用for循環對0-50偶數求和
public static void main(String[] args) {
int sum=0;
for(int a=0;a<50;a++) {
if( a%2==0) {
sum=sum+a;
System.out.println("sum:"+sum);
}
}
}
四、while循環格式
1、基本格式
while(判斷條件語句) {
循環體語句;
}
2、擴展格式
初始化語句;
while(判斷條件語句) {
循環體語句;
控制條件語句;
}
public static void main(String[] args) {
int x=1; //初始化語句
while(x<=10) { //判斷條件語句
System.out.println("HellloWorld"); //循環體語句
x++; //控制條件語句
}
}
五、Do…while 循環語句
1、基本格式
do {
循環體語句;
}while((判斷條件語句);
2、擴展格式
初始化語句;
do {
循環體語句;
控制條件語句;
} while((判斷條件語句);
public static void main(String[] args) {
int a=0;
do {
System.out.println("helloworld");
a++;
}while(a<=5);
}
}
六、三種循環的區別
①do…while循環至少會執行一次循環體。
②for循環和while循環只有在條件成立的時候纔會去執行循環體
for循環語句和while循環語句的小區別:
**使用區別:**控制條件語句所控制的那個變量,在for循環結束後,就不能再被訪問到了,而while循環結束還可以繼續使用,如果你想繼續使用,就用while,否則推薦使用for。
原因:for循環結束,該變量就從內存中消失,能夠提高內存的使用效率。
七、關於break和continue的使用場景與作用
1、break的使用場景:
在選擇結構switch語句中
在循環語句中
離開使用場景的存在是沒有意義的
break的作用:
跳出單層循環
2、continue的使用場景
在循環語句中
離開使用場景的存在是沒有意義的
continue的作用:
單層循環對比break,然後總結兩個的區別
break 退出當前循環
continue 退出本次循環
public static void main(String[] args) {
for (int x = 1; x <= 10; x++) {
if (x % 3 == 0) {
//break;
continue;
}
System.out.println("helloworld");
//break 時輸出x=1,x=2 一共兩次
//continue 時 x=3,x=6,x=9時停止本次循環繼續下一循環,一共七次
}
}