【if语句】
三种格式
1.
if(条件表达式)
{
执行语句;
}
2.
if(条件表达式)
{
执行语句;
}
else
{
执行语句;
}
3.
if(条件表达式)
{
执行语句;
}
else if(条件表达式)
{
执行语句;
}
...
else
{
执行语句;
}
格式:
switch(条件表达式)
{
case 取值1:
执行语句;
break;
case 取值2:
执行语句;
break;
......
default:
执行语句;
break;
}
三种格式
1.
if(条件表达式)
{
执行语句;
}
2.
if(条件表达式)
{
执行语句;
}
else
{
执行语句;
}
3.
if(条件表达式)
{
执行语句;
}
else if(条件表达式)
{
执行语句;
}
...
else
{
执行语句;
}
class IfDemo
{
public static void main(String[] args)
{
int x = 1;
if(x > 1)
{
System.out.println("x > 1");
}
else if(x < 1)
{
System.out.println("x < 1");
}
else
{
System.out.println("|x| <= 1");
}
/*
if else 结构 简写格式: 变量 = (条件表达式)?表达式1:表达式2;
三元运算符:
好处:可以简化if else代码。
弊端:因为是一个运算符,所以运算完必须要有一个结果。
*/
System.out.println(x>1?"yes":"no");
}
}
下面进行一个练习:
class IfTest
{
public static void main(String[] args)
{
//需求1:根据用户定义的数值不同,打印对应的星期英文。
int num = 1;
if(num == 1)
System.out.print("monday");
else if(num == 2)
System.out.println("tuesday");
else if(num == 3)
System.out.println("wednesday");
else if(num == 4)
System.out.println("thursday");
else if(num == 5)
System.out.println("friday");
else if(num == 6)
System.out.println("Saturday");
else
System.out.println("sunday");
}
}
【switch语句】
格式:
switch(条件表达式)
{
case 取值1:
执行语句;
break;
case 取值2:
执行语句;
break;
......
default:
执行语句;
break;
}