Java-03 -控制结构
- 简 介
- 下 载
- 留 言
- 说 明
Java中控制结构(control flow)的语法与C类似。它们都使用{}来表达隶属关系。
选择结构 (if)
1 2 3 4 5 6 7 8 9 10 11 12 |
if (conditon1) { statements; ... } else if (condition2) { statements; ... } else { statements; ... } |
上面的condition是一个表示真假值的表达式。statements;是语句。
练习 写一个Java程序,判断2013年是否是闰年。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
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)
1 2 3 4 5 |
while (condition) { statements; } |
循环 (do... while)
1 2 3 4 5 |
do { statements; }while(condition); // 注意结尾的; |
循环 (for)
1 2 3 4 5 |
for (initial; condition; update) { statements; } |
跳过或跳出循环
在循环中,可以使用
1 2 |
break; // 跳出循环 continue; // 直接进入下一环 |
练习 写一个Java程序,计算从1加2,加3…… 一直加到999的总和
1 2 3 4 5 6 7 8 |
public int intSum(){ int total = 0; for(int i = 1;i<1000;i ++){ total += i; } System.out.println("1加到1000结果为:" + total); return total; } |
选择 (switch)
1 2 3 4 5 6 7 8 9 10 11 12 |
switch(expression) { case 1: statements; break; case 2: statements; break; ... default: statements; break; } |