文章来源: 本文章里面的实例代码来源于毕向东老师Java基础教程
本片文章,主要讲述java基础知识中的if语句的相关基础,知识点是自己总结的,实例代码是来源于毕向东老师的java基础视频的源码
知识点一:
if的语法 : if(){
}
解释: 括号里面最后的返回值是一个布尔类型的变量、表达式、或者返回值给布尔类型的函数
语法简写: 当花括号里面只写一行代码的时候,可以省略花括号 语法为 if()
知识点二:
if...else的语法: if(){} else{}
解释:当if判断条件为真(true)时,进入if;若当if判断条件为假(false)实,则进入else
语法简写: 当花括号里只写一行代码的时候,可以省略花括号 ,语法为 if() else
知识点三:
语法:
if (logic expression)
{
statements…
}
else if(logic expression)
{
statements…
}
案例:
案例一:
class IfDemo
{
public static void main(String[] args)
{
int x = 1;
if(x>1)
{
System.out.println("yes");
}
else
{
System.out.println("a");
}
/*
if else 结构 简写格式: 变量 = (条件表达式)?表达式1:表达式2;
三元运算符:
好处:可以简化if else代码。
弊端:因为是一个运算符,所以运算完必须要有一个结果。
*/
int a = 9,b;
b = (a>1)?100:200;
if(a>1)
b = 100;
else
b = 200;
int n = 3;
if(n>1)
System.out.println("a");
else if(n>2)
System.out.println("b");
else if(n>3)
System.out.println("c");
else
System.out.println("d");
/*
if(n>1)
System.out.println("a");
if(n>2)
System.out.println("b");
if(n>3)
System.out.println("c");
else
System.out.println("d");
*/
System.out.println("over");
}
}
案例二:
class IfTest
{
public static void main(String[] args)
{
//需求1:根据用户定义的数值不同。打印对应的星期英文。
/*
int num = 1;
if(num==1)
System.out.println("monday");
else if(num==2)
System.out.println("tsd");
else
System.out.println("nono");
*/
//需求2:根据用于指定月份,打印该月份所属的季节。
//3,4,5 春季 6,7,8 夏季 9,10,11 秋季 12, 1, 2 冬季
int x = 4;
if(x==3 || x==4 || x==5)
System.out.println(x+"春季");
else if(x==6 || x==7 || x==8)
System.out.println(x+"夏季");
else if(x==9 || x==10 || x==11)
System.out.println(x+"秋季");
else if(x==12 || x==1 || x==2)
System.out.println(x+"冬季");
else
System.out.println(x+"月份不存在");
if(x>12 || x<1)
System.out.println(x+"月份不存在");
else if(x>=3 && x<=5)
System.out.println(x+"春季");
else if(x>=6 && x<=8)
System.out.println(x+"夏季");
else if(x>=9 && x<=11)
System.out.println(x+"秋季");
else
System.out.println(x+"冬季");
}
}