再程序开发过程中一共会存在三种程序逻辑:顺序结构,分支结构和循环结构。
顺序结构即所有的程序按照定义的代码顺序依次执行。
1.if分支结构
if分支结构主要是针对于关系表达式进行判断处理的分支操作,对于分支语句主要有三种使用形式,使用的关键字就是我们的if和else。
(1)if (布尔表达式){//单条件判断
}
(2)if(布尔表达式){//单条件判断
}else{
}
(3)if(布尔表达式){//多条件判断
}else if(布尔表达式){
}else if(布尔表达式)……
2.switch分支结构
一条if语句解决了根据一个条件进行判断所形成的两路分支的流程控制问题,如果条件多于两条,则必须用多条if语句实现所需要的功能,但是此时结构不清楚,不简洁,此时可采用switch语句根据表达式的取值决定控制程序的多路分支流程。switch语句的格式如下:
public class Hello{
public static void main(String args[]){
int x=5;
String str;
switch(6){
case 1:str="1";break;//追加break执行完一个case之后,语句就跳出switch语句
case 2:str="2";break;
case 3:str="3";break;
case 4:str="4";break;
case 5:str="5";break;
default:str="你好!";/*如果switch中的表达式再case中没有匹配的,则执行default之后的语句*/
}
System.out.println("str="+str);
}
}
注意:switch语句中,表达式和表达式常量的数据类型只能是整数或者字符类型,不能为布尔类型。
3.while循环结构
while循环语句的语法格式如下:
public class Hello{
public static void main(String args[]){
int x=5;
String str="Hello world";
while(x>=5)//while循环语句
{
System.out.println("str="+str);
break;
}
}
}
4.do-while循环结构
do-while循环结构如下:
public class Hello{
public static void main(String args[]){
int x=5;
String str="Hello world";
do{
System.out.println("str="+str);
x++;
}while(x<=5);
}
}
5.for循环结构
.for循环结构如下:
public class Hello{
public static void main(String args[]){
int x=5;
String str="Hello world";
for(int i=0;i<x;i++)
{
System.out.println(str+(i+1));
}
}
}
6.转移语句
Java语言提供三种无条件转移语句,return、break、continue。其中return用于从方法中返回值,break语句是直接跳出循环,continue语句则是跳出本次循环。