while 循环:
while循环是一种控制结构,可以让你重复执行任务的若干次。
语法
while循环的语法是:
while(Boolean_expression)
{
//Statements
}
do … while循环:
do… while 循环类似于 while 循环,不同的是do … while循环是保证至少执行一次。
语法
do … while循环的语法是:
do
{
//Statements
}while(Boolean_expression);
for 循环:
for循环是一个循环控制结构,可以有效地编写需要执行的特定次数的循环。
当知道任务要多少次重复,一个for循环是非常有用的。
语法
for循环的语法是:
for(initialization; Boolean_expression; update)
{
//Statements
}
改进Java的for循环:
从Java5中开始增强了for循环。这主要是用于数组。
语法
增强的for循环的语法是:
for(declaration : expression)
{
//Statements
}
break关键字:
关键字break用于停止整个循环。Break关键字必须使用在任何循环或switch语句中。
Break关键字将停止最内层循环的执行,并开始执行的下一行代码块之后的语句。
continue关键字:
continue关键字可以在任一环的控制结构可以使用。它会导致循环立即跳转到循环的下一次迭代。
在for循环中,continue关键字使流程控制立即跳转到update语句。
在while循环或do/while循环,流控制立即跳转到布尔表达式。
语法
continue关键字是在任何环路内的单个语句,其语法如下:
continue;
if 语句:
if 语句包含一个布尔表达式后跟一个或多个语句。
语法
一个if语句的语法:
if(Boolean_expression)
{
//Statements will execute if the Boolean expression is true
}
if…else 语句:
if语句可以跟着一个可选的else语句,当else执行时,if 中布尔表达式是假的。
语法
if…else 的语法是:
if(Boolean_expression){
//Executes when the Boolean expression is true
}else{
//Executes when the Boolean expression is false
}
if…else if…else 语句:
if 语句可以跟着一个可选的 else if … else 语句,这是非常有用的,使用单一的 if…else if 语句以测试各种条件。
语法
if…else 的语法是:
if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
}else if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}else if(Boolean_expression 3){
//Executes when the Boolean expression 3 is true
}else {
//Executes when the one of the above condition is true.
}
嵌套 if…else 语句:
嵌套if-else语句始终是合法的。当要 if , else if , else else语句时有几点要牢记。
一个 if 可以有零或一个else,它必须跟从 else if 之后。
一个 if 可以零个或多个 else if ,它们必须在 else 之前。
一旦一个 else if 条件成功,其他剩余的 else if 或 else 将不会被测试。
语法
嵌套 if…else 的语法如下:
if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}
}
switch 语句:
switch语句允许一个变量来反对值列表平等的进行测试。每个值被称为一个的情况(case),该变量被接通检查每种情况。
语法
switch 的语法是:
switch(expression){
case value :
//Statements
break; //optional
case value :
//Statements
break; //optional
//You can have any number of case statements.
default : //Optional
//Statements
}