第二章 if语句

来源:互联网 发布:pi开关电源设计软件 编辑:程序博客网 时间:2024/06/15 04:33

三种流程结构{顺序、分支、循环}

这里主要说是分支:

分支结构的if

if条件判断语句  

if(表达式){语句块}  如果表达式的值是true 则执行语句块代码,否则跳过语句块。

// if 判断语句import java.util.*;public class IfDemo{public static void main(String[] args){Scanner sc = new Scanner(System.in);System.out.println("请输入你的年龄:");int age = sc.nextInt();if(age>=18){System.out.println("成年 可以上网了 !");}if(age<18){System.out.println("未成年,回家吧!");}}}
// 输入男女 打印 boy girlimport java.util.*;public class IfDemo{public static void main(String[] args){Scanner sc = new Scanner(System.in);System.out.println("请输入男女:");String a = sc.nextLine();boolean b;//.equals 用来判断字符串 == 只是用来判断内存地址 if(a.equals("男")){System.out.println("boy");}if(a.equals("女")){System.out.println("girl");}}}
// 输入分数 看是什么成绩 import java.util.*;public class IfDemo{public static void main(String[] args){Scanner sc = new Scanner(System.in);System.out.println("请输入你的分数:");Double a = sc.nextDouble();if(a>=80){System.out.println("优秀!");}if(a<80 && a>=70){System.out.println("良好");}if(a<70 && a>=60){System.out.println("及格");}if(a<60){System.out.println("不及格,要努力!");}}}

if else 双分支选择结构

if(表达式){语句块}else{语句块2} 如果表达式的值为true执行语句块一1,否则执行语句块2

// if else 结构import java.util.*;public class IfDemo{public static void main(String[] args){Scanner sc = new Scanner(System.in);System.out.println("输入你的年龄:");int a = sc.nextInt();if(a>=18){System.out.println("恭喜你可以上网!");}else{System.out.println("回家吧!");}}}
// 随机产生一个数 计算圆的面积和周长public class IfElseDemo{public static void main(String[] args){//产生随机数 double r = Math.random()*4;//计算面积 Math.pow  次幂double area = Math.PI*Math.pow(r,2);//计算周长double circle = Math.PI*2*r;//拼接 System.out.println("圆的面积是:"+area+"\n圆的周长是:"+circle);if(area>=circle){System.out.println("圆的面积大于或等于周长!");}else{System.out.println("圆的面积小于周长!");}System.out.println(Math.PI);}}
可以看出 if else 做这个运算不严谨 所以有下面

if  else if  else多分支选择结构

if(表达式){语句块1}else if(表达式2){语句块2}.........else{语句块n}   如果表达式1成立执行语句块1在如果表达式2成立则执行语句块2 都不成力的话执行else语句块n。

// 随机数 看是什么年龄public class IfElseDemo{public static void main(String[] args){// 随机一个0到99的数int age=(int)(Math.random()*100);System.out.println("你的年龄是:"+age);//多重选择 只会选择其中一种  if(age<15){System.out.println("儿童 好好玩");}else if(age <25){System.out.println("青年 努力学习!");}else if(age<45){System.out.println("中年 努力工作");}else if(age<65){System.out.println("中老年 补钙");}else if(age<85){System.out.println("老年 多运动");}else {System.out.println("恭喜你");}}}



原创粉丝点击