一、分支结构之单分支

第一种:if语句
if(条件){
    执行语句
}

第二种:if    else if语句
if(条件){
     执行语句
}else if(条件){
    执行语句
}else{
    执行语句
}

注意:if里面的条件结果是boolean值。即true 执行,false不执行。

二、分支结构之多分支

多分支语句之:switch ...... case
switch(值){
case  值1:
    执行语句;
    break;
case  值2:
   执行语句;
   break;
default:
  执行语句;
}
分析:
1.这种结构类似于已经知道很多值得情况,然后一一对比较,作出执行结果。
2.switch(值),只能是byte、short、int 、char。jdk1.5版本支持enum,jdk1,7以后支持String字符串。
3.可以不用break。用break作用是终止语句,找到正确的case值不在继续执行下面的语句。

三、单分支与多分支的区别
if(值){}  else if(值){},好处是可以写复杂的逻辑,不好处执行速度慢。
switch case,好处是执行效率高,但是switch的变量值与case值只能做是否相等运算,即 == 。

四、循环结构

 1.for循环结构及演示

结构:括号里的;号不能省略,但可以省略值。
for(; ; ){
 
}
比如:鸡兔同笼问题。鸡与兔子总数50只,总共100只脚,问鸡、兔各多少只?
public class Demo{
 public static void main(String[] args){
  for(int x=1;x<=50;x++){
    if(x*2+(50-x)*4 == 100){
      System.out.println("鸡的个数:" +x + "兔子的个数是:" + (100-x));
   }
  }   
 }
}
for循环演示水仙花:去取出个位、十位、百位的数字,三次方相加等于本身。
public class Demo{
     public static void main(String[] args){
     int count = 0;
     for(int x=100;x<1000;x++){
	int bai=x/100;
	int shi=x%100/10;
	int ge=x%10;
     	if(bai*bai*bai + shi*shi*shi +ge*ge*ge == x){
		System.out.println(x);
		count++;
	}
   }
	System.out.println("总共"+count+"数字");
  }  
 }

  

2.for嵌套循环结构及演示

for(; ;){
  for(; ;){
  
 }
}
说明:循环里面套一层循环。通过练习输出不同“*”练习此语句。
练习打出下列图案:
*
**
***
****
public class Demo{
 public static void main(String[] args){
     for(int i=1;i<=4;i++){
      for(int j=1;j<=i;j++){
       System.out.print("*");
   }
    System.out.println();
  }  
 }
}

  

fou嵌套循环之9*9乘法表演示:
public class Demo{
 public static void main(String[] args){
     for(int i=1;i<=9;i++){
      for(int j=1;j<=i;j++){
       System.out.print(j +"*" +i + "=" + i*j +" ");
   }
    System.out.println();
  }  
 }
}

  

while结构:
初始值
while(终点判定条件,只有一个){
 执行语句;
 变化量;
}
do while 结构:
do{
 执行语句;
}while(终点判断条件)

  

相关文章:

  • 2021-05-19
  • 2022-12-23
  • 2022-12-23
  • 2021-09-28
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-02-13
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案