java基础-流程控制

流程控制语句

  • if...else...
  • while
  • do...while....
  • switch case
  • for
  • foreach
  • loop

1. if...else...

使用方法为

if(条件)

{

  满足条件时执行的块

}else{

  不满足条件时执行的块

}

实例:

public class test{
    public static void main(String args[]){
        int a,b;
        Scanner s=new Scanner(System.in);
        System.out.println("请输入a");
        String a = s.nextInt();
        System.out.println("请输入b");
        String b = s.nextInt();
        
        if(a>=b){
            System.out.println("a大于等于b,因为"+a+"大于等于"+b);
        }else{
            System.out.println("a小于b,因为"+a+"小于"+b);
        }
    }    
}

2. while

使用方法为:

while(判断条件)
{
满足条件后执行的代码块;
}
//执行完后会再一次的判断条件是否满足,不满足将继续下一段代码,满足则继续执行大括号中的语句

实例:

public class test{
    public static void main(String args[]){
        int a,b;
        Scanner s=new Scanner(System.in);
        System.out.println("请输入a");
        String a = s.nextInt();
        System.out.println("请输入b");
        String b = s.nextInt();
        while(a<b){
            System.out.println("a大于等于b,因为"+a+"大于等于"+b);
       b++; }
} }

3. do  while

使用方法:

do{
执行的代码
}
while(判断条件)

实例:

 

dowhile与while的区别是,while会先判断条件是否满足,再执行代码。而dowhile无论如何都先执行一次代码,再进行条件判断

4. switch case

条件分支

使用方法

switch(表达式)
{
case 常量值1:代码语句;break;
case 常量值2:代码语句;break;
case 常量值3:代码语句;break;
case 常量值4:代码语句;break;
default:没有满足上述任一条件执行此处
}

实例:

 

public class test{

public static void main(String args[]){
  int a,b;
  Scanner s = new Scanner(System.in);
  System.out.println("请输入a");
  String a = s.nextInt();
  System.out.println("请输入b");
  String b = s.nextInt();
  switch(a){
    case 1:System.out.println("你输入了1");break;//break在此处的含义为:执行代码后跳出整个分支语句。如果不加break,后面的代码依然会被执行
    case 2:System.out.println("你输入了2");break;
    case 3:System.out.println("你输入了3");break;
    }
  }
}

5. for

使用方法:

for(初始化语句;判断条件;递增/递减语句)

{
满足条件时执行的代码块
}

实例:

public class test{
    public static void main(String args[]){
        int a,b;
        Scanner s=new Scanner(System.in);
        System.out.println("请输入a");
        String a = s.nextInt();
        for(;a<100;a++){
       a++;
        }
        System.out.println("循环了"+a+"次");
  }
}

 练习1:判断变量x是奇数还是偶数

public class test{
    public static void main(String args[]){
        Scanner s = new Scanner(System.in)
        int a = s.nextInt();
        if(a%2==1){
            System.out.println(a+"是奇数");
        }else{
            System.out.println(a+"是偶数");
        }
    }
}

 练习2:用for打印菱形

 

posted @ 2020-07-27 23:48  helex  阅读(128)  评论(0编辑  收藏  举报