您的位置:首页 > 编程语言 > Java开发

Java-06-程序逻辑控制

2017-06-20 22:18 141 查看
顺序结构

分支结构
Switch(条件)

Case  condition1:{
 语句;
 break;

}

Case  condition2:{
 语句;
 break;

}

Case  condition3:{
 语句;
 break;

}

Case  condition1:{
 语句;
 break;

}
Default :{ //当不满足任何条件的时候
 语句;
 break;

}

 
注意:如果没有break,switch语句会在执行满足条件的语句后,继续执行接下来的语句。
千万记住,switch不能够判断不二表达式,他只能够判断内容(可以判断String类型,并且区分大小写)。所以我们尽量使用if
…else…

循环结构
1 while循环:分为两种形式语法

While循环:
Do … while循环:
While (循环判断){
           循环语句;

修改循环结束条件;
}
Do{

循环语句;

修改循环结束条件;
} while(循环判断);
记住do while 判断后有分号。

 
范例:使用while循环实现1~100累加

 
  1//求1~100的累加,使用while条件循环语句
  2public classTestDemoIII{
  3   
public static voidmain (String [] args){
  4       
int sum =0;
  5       
int current=1;
  6       
while(current<=100){
  7            sum += current;
  8            current++;
  9        }   
 10        System.out.println(sum);
 11   
}   
 12}  
 
以后开发中请切记彻底忘记do
while
,根本就不会用的。
 
2 for循环
范例:使用for循环实现1~100累加
 
 1//求1~100的累加,使用for条件循环语句
  2public classTestDemoIII{
  3   
public static voidmain (String [] args){
  4       
int sum =0;
  5       
for(int i =1;i<=100;i++){
  6        sum += i;
  7        }
  8    System.out.println(sum);
  9    }
 10}
 

疑问? 在开发中如何选择此两种循环?
 
如果不知道循环次数,但是知道循环结束条件的时候使用while循环。
如果已经明确知道循环次数了,使用for循环。

 
范例:打印一个乘法口诀表 (我去,想了半天才搞出来,真应该多看看)
 
1//求1~100的累加,使用for条件循环语句
  2public classTestDemoIII{
  3   
public static voidmain (String [] args){
  4       
for(int i =1; i <=
9; i++){
  5       
//此for循环控制的是行
  6           
for(int k =1;k <=i;k++){
  7           
//此for循环控制的是列
  8               System.out.print(i +
"*" + k +"="+(i*k) +"  " );
  9            }
 10           System.out.println();
 11        }
 12       
//System.out.println();
 13  }
 14}
 
 

以下是打印结果
 
1*1=1  
2*1=2  2*2=4  
3*1=3  3*2=6  3*3=9  
4*1=4  4*2=8  4*3=12  4*4=16  
5*1=5  5*2=10  5*3=15  5*4=20 5*5=25  
6*1=6  6*2=12  6*3=18  6*4=24 6*5=30  6*6=36  
7*1=7  7*2=14  7*3=21  7*4=28 7*5=35  7*6=42  7*7=49  
8*1=8  8*2=16  8*3=24  8*4=32 8*5=40  8*6=48  8*7=56  8*8=64  
9*1=9  9*2=18  9*3=27  9*4=36 9*5=45  9*6=54  9*7=63  9*8=72  9*9=81  
 
 

Continue 和 break
 
  public class PrintDemo{
        
public static void main(String [] args){
For(int x == 0; x < 10 ; x ++){

If(x == 3){
Continue;  //之后的代码不执行,结束本次循环。

}

System.out.println("x="+ x);

}
         }
 } 
 
 
  public class PrintDemo{
        
public static void main(String [] args){
For(int x == 0; x < 10 ; x ++){

If(x == 3){
break;  //退出整个循环。

}

System.out.println("x="+ x);

}
         }
 } 
 
 

总结
1循环结构需要反复多写几次;
2 while用于不确定次数但知道结束条件的循环,for适用于明确知道循环次数的循环;
3 continue和break使用频率不高,需要和if语句结合使用;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Java 笔记