01 順序結構
public class MyControl {
public static void main(String []args) {
System.out.println("順序結構1");
System.out.println("順序結構2");
}
}
02 循環結構
for循環
public class MyControl {
public static void main(String []args) {
char[] arrays= {'a','b','c'};
for(int i=0;i<arrays.length;i++) {
System.out.println(arrays[i]);
}
}
}
while
public class MyControl {
public static void main(String []args) {
char[] arrays= {'a','b','c'};
int i=0;
while(i<arrays.length) {
System.out.println(arrays[i]);
i++;
}
}
}
do-while
public class MyControl {
public static void main(String []args) {
char[] arrays= {'a','b','c'};
int i=0;
do {
System.out.println(arrays[i]);
i++;
}while(i<arrays.length);
}
}
三種循環的區別:
雖然可以完成同樣的功能,但是還是有小區別:
do…while循環至少會執行一次循環體。
for循環和while循環只有在條件成立的時候纔會去執行循環體
for循環語句和while循環語句的小區別:
使用區別:控制條件語句所控制的那個變量,在for循環結束後,就不能再被訪問到了,而while循環結束還可以繼續使用,如果你想繼續使用,就用while,否則推薦使用for。原因是for循環結束,該變量就從內存中消失,能夠提高內存的使用效率。
03 分支語句
if分支語句
public class MyControl {
public static void main(String []args) {
int a=20;
int b=20;
if(a==b) {
System.out.println(a+"=="+b);
}
}
}
if-else分支語句
public class MyControl {
public static void main(String []args) {
int a=10;
int b=20;
if(a==b) {
System.out.println(a+"=="+b);
}else {
System.out.println(a+"!="+b);
}
}
}
swicth分支結構
package com.my;
import java.util.Scanner;
public class MyControl {
public static void main(String []args) {
Scanner sc = new Scanner(System.in);
System.out.println("請輸入一個數字(1-7):");
int weekday = sc.nextInt();
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;
}
}
}
swich(表達式)中表達式的返回值必須是以下幾種類型之一:
byte,short,char,int,枚舉(jdk1.5),String(jdk1.7)
04 跳轉語句
break
跳出單層循環
continue
結束一次循環,繼續下一次的循環
return
可以從一個方法返回,並把控制權交給調用它的語句。
直接結束整個方法,從而結束循環。