------- android培训、java培训、期待与您交流! ----------
程序流程控制
Java语句执行的4中结构:顺序结构,判断结构,选择结构,循环结构。
一、顺序结构:按照代码从上至下的顺序依次执行。
二、判断结构:(if语句)
1.
if(条件表达式)
{
执行语句;
}
当条件表达式结果为ture时,才执行"{ }"内的执行语句。并且,如果执行语句只有一条,可以不写"{ }",直接书写执行语句。(对于初学者,建议不要省略大括号)
2.
if(条件表达式)
{
执行语句A;
}
else
{
执行语句B;
}
当条件表达式结果为true时,执行语句A,否则,执行语句B。即A和B有且只有一个能够执行。
注意:if else结构可以简写成: 变量 = (条件表达式)?表达式1:表达式2; 即,使用三元运算符的方式简写代码。
但是:由于三元运算符是一种运算符,所以运算结束后必须要有一个结果。
3.
if(条件表达式)
{
执行语句A;
}
else if(条件表达式)
{
执行语句B;
}
...
else
{
执行语句N;
}
小练习:
class IfTest
{
public static void main(String[] args)
{
judge(5);
}
public static void judge(int day)
{
if (day==0)
System.out.println("Sunday");
else if(day==1)
System.out.println("Monday");
else if(day==2)
System.out.println("Tuesday");
else if(day==3)
System.out.println("Wednesday");
else if(day==4)
System.out.println("Thirsday");
else if(day==5)
System.out.println("Friday");
else
System.out.println("Satuary");
}
}
练习:
class Day2Month
{
public static void main(String[] args)
{
int year = 2000;
int month = 2;
if (month<1 || month>12)
System.out.println("没有这个月份,请重新输入");
else if (month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12)
System.out.println(year+"年"+month+"月有31天");
else if (month==4 || month==6 || month==9 || month==11)
System.out.println(year+"年"+month+"月有30天");
else
if (year%4==0 && year%100!=0 || year%400==0)
System.out.println(year+"年"+month+"月是闰月,共有29天");
else
System.out.println(year+"年"+month+"月有28天");
}
}
三、选择结构(switch语句)
格式:swich(表达式)
{
case 取值1:
执行语句;
break;
case 取值2:
执行语句;
break;
...
default:
执行语句;
break;
}
switch语句的特点:
1.switch语句选择的类型只有四种:byte、short、int、char;
2.case之间与default没有顺序。先执行第一个case,没有匹配的case执行default;
3.结束switch语句的两种情况:遇到break 或者 执行到switch语句结束。
4.如果匹配的case或者default没有对应的break,那么程序会继续向下执行,运行可以执行的语句,直到遇到break或者switch结尾结束。
练习:
class SwitchTest
{
public static void main(String[] args)
{
int x = 13;
switch(x)
{
case 3:
case 4:
case 5:
System.out.println(x+"春季");
break;
case 6:
case 7:
case 8:
System.out.println(x+"夏季");
break;
case 9:
case 10:
case 11:
System.out.println(x+"春季");
break;
case 12:
case 1:
case 2:
System.out.println(x+"春季");
break;
default:
System.out.println("没有这个月份");
}
}
}
if和switch语句很像,具体什么场景下应用什么语句呢?
如果判断的具体数值不多而且符合byte、short、int、char这四种类型(JDK1.7以后,加入String类型),虽然两个语句都可以使用,但是建议使用switch语句。因为效率稍高。
其他情况:对区间判断,对结果为boolean类型判断,使用if。if的使用范围更广。