java 选择结构if

if条件语句分为三种语法格式,每一种格式都有它自身的特点

1.if语句

if语句是指如果满足某种条件,就进行某种处理

公式:

if (条件语句){

   执行语句;

   ……

}

1 public class Pd{
2     public static void main(String[] args){
3         int time = 5;
4         if(time<7){
5             System.out.println("闹钟响了,该起床了!");
6         }
7     }
8 }

结果:会输出闹钟响了,该起床了!

2.if…else语句

if (判断条件){

   执行语句1

   ……

}else{

   执行语句2

   ……

}

 1 public class Pd {
 2 
 3     public static void main(String[] args) {
 4         int a = 4,b = 7; //定义两个int整型变量
 5         int max;
 6         if(a>b){
 7             max = a;
 8         }else{
 9             max = b;
10             System.out.println(max);
11         }
12     }      
13 }

结果:会输出7

3.if…else if…else语句

if (判断条件1) {

   执行语句1

} else if (判断条件2) {

   执行语句2

}

...

else if (判断条件n) {

   执行语句n

} else {

   执行语句n+1

}

 1 public class Pd{
 2     public static void main(String[] args){
 3         int score = 103;
 4         if(score>=90 && score<=100){
 5             System.out.println("优秀");
 6         }else if(score>=60 && score<90){
 7             System.out.println("合格");
 8         }else if(score>=0 && score<60){
 9             System.out.println("不及格");
10         }else{
11             System.out.println("错误或异常");
12         }
13     }
14 }

结果:会输出错误或异常

 

 

 

posted @ 2017-12-12 17:58  叶墨悻  阅读(525)  评论(0编辑  收藏  举报