Java-03 -控制结构

Java中控制结构(control flow)的语法与C类似。它们都使用{}来表达隶属关系。
选择结构 (if)

if (conditon1) {
  statements;
    ...
}
else if (condition2) {
  statements;
    ...
}
else {
  statements;
    ...
}

上面的condition是一个表示真假值的表达式。statements;是语句。
练习 写一个Java程序,判断2013年是否是闰年。

public class leapyear{
 
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sca=new Scanner(System.in );
		System.out.println("请输入一个 年份");
		long year=sca.nextLong();
		if(year % 4== 0 && year%100!=0||year%400==0)
		{
			System.out.println(year+"是闰年!");
		}
		else
		{
			System.out.println(year+"不是闰年!");
		}
       }
}
循环 (while)
while (condition) {

statements;

}


循环 (do... while)

do {

statements;

}while(condition);  // 注意结尾的;


循环 (for)

for (initial; condition; update) {

statements;

}


跳过或跳出循环

在循环中,可以使用

break; // 跳出循环
continue; // 直接进入下一环

练习 写一个Java程序,计算从1加2,加3…… 一直加到999的总和

public int intSum(){
    int total = 0;
    for(int i = 1;i<1000;i ++){
        total += i;
    }
    System.out.println("1加到1000结果为:" + total);
    return total;
}


选择 (switch)

switch(expression) {
case 1:
    statements; 
    break; 
case 2:
    statements; 
    break; 
...
default:
    statements; 
    break; 
}