[javase学习笔记]-3.1 if语句

来源:互联网 发布:linux sz查看进度 编辑:程序博客网 时间:2024/05/16 03:30

这一节我学习java语言中的流程控制语句之中的判断语句.

首先我们看看if语句的不同格式

看下面的代码

class  IfDemo{public static void main(String[] args) {//判断语句/**************************************if语句的第一种格式:if(条件表达式){执行语句;}*/int x = 3;if(x > 1){//如果没有大括号,if就只能控制离它最近的那条语句System.out.println("yes");}/**************************************if语句的第二种格式:if(条件表达式){执行语句;}else//否则{执行语句;}*/if(x > 1){System.out.println("yes");}else{System.out.println("no");}int a = 3,b;if(a>1)b = 100;elseb = 200;//b = a>1?100:200;//三元运算符就是if else的语句简写格式.//简写格式什么时候用?//当if else运算后有一个具体结果时,可以简化写成三元运算符.System.out.println("b="+b);/*****************************************if语句的第三种格式:if(条件表达式){执行语句;}else if(条件表达式){执行语句;}......else{执行语句;}只有一个代码块被执行*/}}

从上面的代码我们看到了三种不同格式的if语句,看到了三元运算符就是if else的语句简写格式.并且是当if else运算有一个具体结果时可以互用.


我们再看一下代码块的作用吧

public static void main(String[] args) {int m = 89;//两个打印都打印/*局部代码块可以定义局部变量的生命同期。*/{//局部代码块int n = 89;//n的作用域是这个代码块System.out.println(m);System.out.println(n);}System.out.println(m);System.out.println(n);//提示找不到变量n,这就说明n的作用域就是上面的代码块}

结果:


从结果看到了代码块中变量出了代码块就已经被释放掉了,也就是说代码块中定义的局部变量的作用域就是代码块.


最后我们看一个if语句的小例子.

class IfTest2 {public static void main(String[] args) {/*一年有四季。春季:3 4 5夏季:6 7 8秋季:9 10 11冬季:12 1 2根据用户输入的月份,给出对应的季节。*/int month=12;if(month<1 || month>12)System.out.println(month+"月没有对应的季节");else if(month>=3 && month<=5)System.out.println(month+"月是春季");else if(month>=6 && month<=8)System.out.println(month+"月是夏季");else if(month>=9 && month<=11)System.out.println(month+"月是秋季");elseSystem.out.println(month+"月是冬季");if(month==3||month==4||month==5)System.out.println(month+"月是春季");else if(month==6||month==7||month==8)System.out.println(month+"月是夏季");else if(month==9||month==10||month==11)System.out.println(month+"月是秋季");else if(month==12||month==1||month==2)System.out.println(month+"月是冬季");elseSystem.out.println(month+"月没有对就的季节");}}
输出结果两个都是冬季.




0 0