一般来说程序的结构分三种:顺序结构,选择结构和循环结构。这篇文章来总结一些知识点。
一.顺序结构
程序从上至下逐行执行,一条语句执行完之后继续执行下一条语句,一直到程序的最后。在程序设计中经常使用到的结构。
二.选择结构
选择结构是要根据条件的成立与否决定要执行哪些语句的一种结构。选择结构包括if,if…else和switch语句。如下图
public static void main(String[] args) {
// TODO Auto-generated method stub
int x = 10;
if(x < 20){
System.out.println("这是if语句");
}
}
程序运行结果为:
这是if语句
public static void main(String[] args) {
// TODO Auto-generated method stub
int x = 30;
if(x < 20){
System.out.println("这是if语句");
}else{
System.out.println("这是if....else语句");
}
}
程序运行结果为:
这是if…else语句
public static void main(String[] args) {
// TODO Auto-generated method stub
char z = '+';
switch(z){
case '+':{
System.out.println("这是switch语句");
break;
}
case '-':{
break;
}
case '*':{
break;
}
case '/':{
break;
}
default:{
break;
}
}
}
程序运行结果为:
这是switch语句
三.循环结构
循环结构有三种:while,do…while,for。
public static void main(String[] args) {
// TODO Auto-generated method stub
int x = 1;
int sum = 0;
while(x <= 10){
sum += x;
x++;
}
System.out.println("sum = " + sum);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int x = 1;
int sum = 0;
do{
sum += x;
x++;
}while(x <= 10);
System.out.println("sum = " + sum);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int sum = 0;
for(int x = 1;x <= 10;x++){
sum += x;
}
System.out.println("sum = " + sum);
}
程序运行结果都是sum = 55
循环的嵌套
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int x = 1;x <= 9;x++){
for(int j = 1;j <= x;j++){
System.out.print(x + "*" + j + "=" + (x*j) +"\t");
}
System.out.print("\n");
}
}
程序运行结果为:
11=1
21=2 22=4
31=3 32=6 33=9
41=4 42=8 43=12 44=16
51=5 52=10 53=15 54=20 55=25
61=6 62=12 63=18 64=24 65=30 66=36
71=7 72=14 73=21 74=28 75=35 76=42 77=49
81=8 82=16 83=24 84=32 85=40 86=48 87=56 88=64
91=9 92=18 93=27 94=36 95=45 96=54 97=63 98=72 9*9=81
循环中断有二个关键字:break和continue
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int x = 1;x <= 9;x++){
if(x == 3){
break;
}
System.out.println("x = " + x);
}
}
程序运行结果为:
x = 1
x = 2
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int x = 1;x <= 9;x++){
if(x == 3){
continue;
}
System.out.println("x = " + x);
}
}
程序运行结果为:
x = 1
x = 2
x = 4
x = 5
x = 6
x = 7
x = 8
x = 9