流程控制:
Java的分支结构:
1、if语句
结构:if(布尔表达式){布尔表达式为true时要执行的语句 }
例如:public static void main(String[] args) {
int i =10;
if(i<20){
System.out.println("i<20");
}
}
结果输出:i<20
public static void main(String[] args) {
int i =30;
if(i<20){
System.out.println("i<20");
}
System.out.println("i>=20");
}
结果输出:i>=20
结构:if(布尔表达式){
布尔表达式为true时要执行的语句
}else{
布尔表达式为false时要执行的语句
}
例如:publicstaticvoidmain(Stringargs[]){
intx = 30;
if(x < 20){
System.out.print("这是 if 语句");
}else{
System.out.print("这是 else 语句");
}
}
结果输出:这是else语句
结构:if(布尔表达式1){
布尔表达式1为true时要执行的语句
}elseif(布尔表达式2){
布尔表达式2为true时要执行的语句
}
else if(布尔表达式2){
布尔表达式2为true时要执行的语句
}else{
如果以上布尔表达式都为false则执行这里的代码
}
例如:public static void main(String args[]){}
结果输出:Value of X is 30
嵌套式if语句:
结构:if(布尔表达式 1){
//如果布尔表达式 1的值为true执行代码
if(布尔表达式 2){
如果布尔表达式 2的值为true执行代码
}
}
例如:public static void main(String args[]){
int x = 30;
int y = 10;
if( x == 30 ){
if( y == 10 ){
System.out.print("X = 30 and Y = 10");
}
}
}
结果输出:X = 30 and Y = 10
2、switch语句:
结构:switch(变量){
case value1:变量=value1时执行的语句;break;
case value2:变量=value2时执行的语句;continue;
、、、
default:default语句;
}
switch语句的使用规则:
switch语句中的变量类型可以是:byte、short、int、char。(从 Java SE 7 开始,switch 支持字符串类型了,同时 case 标签必须为字符串常量或字面量。)
switch可以拥有多个case语句。
case语句中的值的数据类型必须与变量的数据类型相同,而且只能是常量或字面常量。
当变量的值与case语句相等时,那么case语句之后的语句开始执行,直到break语句出现才会跳出switch语句。
switch语句可以包含一个default分支,该分支必须是switch语句的最后一个分支,default在所有case语句没有遇到break时执行完后都必须执行,它不需要break语句。
例:public static void main(String args[]){
int x = 30;
switch(x){
case 1:
System.out.println(x);
case 30:
System.out.println(x);
default:
System.out.println("x");
}
}
结果输出:30
x
注意:
break语句的作用:
1、只能在循环体内和switch语句体内使用break语句。
2、当break出现在循环体中的switch语句体内时,其作用只是跳出该switch语句体。
3、当break出现在循环体中,但并不在switch语句体内时,则在执行break后,跳出本层循环体。
4、在循环结构中,应用break语句使流程跳出本层循环体,从而提前结束本层循环。
continue语句作用:
1、continue语句一般形式为:contonue;
2、其作用是结束本次循环,即跳过本次循环体中余下尚未执行的语句,接着再一次进行循环的条件判定。
3、注意:执行continue语句并没有使整个循环终止。在while和do-while循环中,continue语句使得流程直接跳到循环控制条件的测试部分,然后决定是否继续进行。
4、在for循环中,遇到continue后,跳过循环体中余下的语句,而去对for语句中的“表达式3”求值,然后进行“表达式2”的条件测试,最后根据“表达式2”的值来决定for循环是否执行。循环体内,不论continue是作为何种语言的语句成分,都按上述功能执行,这点与bresk有所不同。
案例:打印一个菱形*边框
public class Demo {
int a,b; //a是要生成的菱形行数
int h; //h是方法中的参数,也是行数
int i,j; //i j是循环结构参数
public void draw(int h ){
for(i = 1 ;i <= h ;i++){ //逐行打印
for(j = 1;j <= h;j++){ //每行打印个数与行数保持一致
//下面语句是菱形四条边的函数,在边上的坐标点,打印*,否则打印空格
if(j == (h + 3) / 2 - i || j == (h - 1) / 2 + i || j == i - (h - 1 ) / 2 || j == (3 * h + 1) / 2 - i){
System.out.print("*");
}else{
System.out.print(" ");
}
}
System.out.println(); //第 i 行打印完换行
}
}
public static void main(String[] args){ //静态方法
Demo b = new Demo(); //初始化方法
int a = 35; //赋值并执行draw方法
b.draw(a);
}
}
结果输出:
*
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
*