第三讲:java结构
1.顺序结构
顺序结构就是从上往下依次执行,也是最基础的结构。
如以下程序,就是依次执行HelloWorld1–>HelloWorld2–>HelloWorld3–>HelloWorld4–>HelloWorld5
public class Test{
public static void main(String args[]){
System.out.println("HelloWorld1");
System.out.println("HelloWorld2");
System.out.println("HelloWorld3");
System.out.println("HelloWorld4");
System.out.println("HelloWorld5");
}
}
2.判断结构
- if 判断语句
public class Test{
public static void main(String args[]){
// if(判断条件){
// 输出语句;
// } else if(){
// 输出语句;
// } else{
// 输出语句;
// }
int a=0;
if(a>0 && a<10){
System.out.println("你执行了 a>0 && a<10 的条件");
} else if(a>10){
System.out.println("你执行了 a>0 的条件");
} else{
System.out.println("你执行了 else 的条件");
}
}
}
- switch…case判断语句
import java.util.Scanner;
public class Test{
public static void main(String args[]){
/*
switch(判断条件){
case 特殊值1:
执行语句;
break;
case 特殊值2:
执行语句;
break;
.
.
.
case 特殊值3:
执行语句;
break;
default:
执行语句;
break;
}
*/
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个整数");
int a = sc.nextInt();
switch(a){
case 1:
System.out.println("执行了case 1");
break;
case 2:
System.out.println("执行了case 2");
break;
case 3:
System.out.println("执行了case 3");
break;
default:
System.out.println("执行了default");
break;
}
}
}
switch…case还具有向下穿透性
当没有break时,程序将继续向下执行,且不会再经过case判断,知道遇到break或全部执行完毕后终止。
public class Test{
public static void main(String args[]){
int a = 3
switch(a){
case 1:
System.out.println("执行了case 1");
//break;
case 2:
System.out.println("执行了case 2");
//break;
case 3:
System.out.println("执行了case 3");
//break;
default:
System.out.println("执行了default");
//break;
}
/*
执行结果为:
执行了case 3
执行了default
*/
}
}
3.循环结构
- for循环
public class Test{
public static void main(String args[]){
for(int i=1;i<=1000;i++){
System.out.println("HelloWorld");
}
//执行结果为1000次HelloWorld
}
}
- while循环
public class Test{
public static void main(String args[]){
/*
while(循环条件){
循环体;
条件控制语句;
}
*/
int a=1
while(a<=1000){
System.out.println("HelloWorld");
a++;
}
//执行结果为1000次HelloWorld
}
}
- do while循环
public class Test{
public static void main(String args[]){
/*
do{
循环体;
条件控制语句;
}while(循环条件);
*/
int a=1
do{
System.out.println("HelloWorld");
a++;
}while(a<=1000)}
//执行结果为1000次HelloWorld
}
}
- 死循环
public class Test{
public static void main(String args[]){
/*
for(;;){
循环体;
}
while(true){
循环体;
}
*/
for(;;){
System.out.println("HelloWorld");
}
while(true){
System.out.println("HelloWorld");
}
//将无限执行HelloWorld
//DOS窗口结束循环--> Ctrl+C
}
}