1、for(){}
比较常用的for循环是
for(initialization; condition; iteration) {
// body
}
例:
for(int x = 0; x < 100; x++) {
System.out.println(x);
}
2、while(){}
这种方法是满足条件时才进行循环操作
例:while(x<100)
{
sum ++;
}
3、do{
}while();
这种方法至少会执行一次循环,先执行一种操作,直到满足条件(condition)时才退出这个循环。
例:int sum=0;int n=1;
do{
sum+=n++
}
while(n<=100);
4、switch(x){
case x:System.out.println("");
break;
}
// Using a do-while to process a menu selection
class Menu {
public static void main(String args[])
throws java.io.IOException {
char choice;
do {
System.out.println("Help on:");
System.out.println(" 1. if");
System.out.println(" 2. switch");
System.out.println(" 3. while");
System.out.println(" 4. do-while");
System.out.println(" 5. for\n");
System.out.println("Choose one:");
choice = (char) System.in.read();
} while( choice < '1' || choice > '5');
System.out.println("\n");
switch(choice) {
case '1':
System.out.println("The if:\n");
System.out.println("if(condition) statement;");
System.out.println("else statement;");
break;
case '2':
System.out.println("The switch:\n");
System.out.println("switch(expression) {");
System.out.println(" case constant:");
System.out.println(" statement sequence");
System.out.println(" break;");
System.out.println(" // ...");
System.out.println("}");
break;
case '3':
System.out.println("The while:\n");
System.out.println("while(condition) statement;");
break;
case '4':
System.out.println("The do-while:\n");
System.out.println("do {");
System.out.println(" statement;");
System.out.println("} while (condition);");
break;
case '5':
System.out.println("The for:\n");
System.out.print("for(init; condition; iteration)");
System.out.println(" statement;");
break;
}
}
}
下面是这个程序执行的一个样本输出:
Help on:
1. if
2. switch
3. while
4. do-while
5. for
Choose one:
4
The do-while:
do {
statement;
} while (condition);
在程序中,do-while 循环用来验证用户是否输入了有效的选择。如果没有,则要求用户重新输入。因为菜单至少要显示一次,do-while 循环是完成此任务的合适语句。
关 于此例的其他几点:注意从键盘输入字符通过调用System.in.read( ) 来读入。这是一个Java 的控制台输入函数。尽管Java 的终端 I/O (输入/输出)方法将在第12章中详细讨论,在这里使用System.in.read ( ) 来读入用户的选择。它从标准的输入读取字符(返回整数,因此将返回值choice 定义为字符型)。默认地,标准输入是按行进入缓冲区的,因此在你输入的任何字符被送到你的程序以前,必须按回车键。
Java 的终端输入功能相当有限且不好使用。进一步说,大多数现实的Java 程序和applets (小应用程序)都具有图形界面并且是基于窗口的。因此,这本书使用终端的输入并不多。然而,它在本例中是有用的。另外一点:因为使用 System.in.read ( ) ,程序必须指定throws java.io.IOException 子句。这行代码对于处理输入错误是必要的。这是Java 的异常处理的一部分,将在第10章讨论。
5、if(){continue;}
break 和 continue的用法
6、break;
break 和 continue的用法