While循環(huán)
例子:
import java.util.Arrays;
public class Lx{public static void main(String[] args) {
int x = 10;
while(x < 20){
System.out.print("volue of x : " +x);
x++;
System.out.print("\n");
}
}} ```
##Do While循環(huán)
例子:
import java.util.Arrays;
public class Lx{public static void main(String[] args) {
int x = 10;
do{
System.out.print("value of x : "+x);
x++;
System.out.print("\n");
}while(x<20);
}}```
條件判斷
在Java中條件判斷有兩種形式:if和 switch
if 語句由一個(gè)布爾表達(dá)式后跟一個(gè)或多個(gè)語句組成。
if 語句的語法是:
if(Boolean_expression){ //Statements will execute if the Boolean expression is true}```
如果布爾表達(dá)式的值為 true,那么代碼里面的塊 if 語句將被執(zhí)行。如果不是 true,在 if 語句大括號后結(jié)束后的第一套代碼將被執(zhí)行。
####例子
public class Lx{ public static void main(String args[]){
int x = 10; if(x < 20 )
{ System.out.print("This is if statement");
} } }```
if...else 語句
任何 if 語句后面可以跟一個(gè)可選的 else 語句,當(dāng)布爾表達(dá)式為 false,語句被執(zhí)行。
if...else 的語法是:
if(Boolean_expression){
//Executes when the Boolean expression is true}else{
//Executes when the Boolean expression is false}```
####例子
public class Lx{ public static void main(String args[]){
int x = 30;
if( x < 20){
System.out.print("This is if statement");
}else{System.out.print("This is else statement");}
} } ```
當(dāng)使用 if , else if , else 語句時(shí)有幾點(diǎn)要牢記。
一個(gè) if 語句可以有0個(gè)或一個(gè) else 語句 且它必須在 else if 語句的之后。
一個(gè) if 語句 可以有0個(gè)或多個(gè) else if 語句且它們必須在 else 語句之前。
一旦 else if 語句成功, 余下 else if 語句或 else 語句都不會被測試執(zhí)行。
例子
public class Lx{ public static void main(String args[]){
int x = 30;
if ( x == 10){
System.out.print("Value of x is 10");
}else if ( x == 20){
System.out.print("Value of x is 20");
}else if ( x == 30){
System.out.print("Value of x is 30");
}else{
System.out.print("This is else statement");
}
} } ```
####嵌套 if...else 語句與邏輯與(&&)
它始終是合法的嵌套 if-else 語句,這意味著你可以在另一個(gè) if 或 else if 語句中使用一個(gè) if 或 else if 語句。
#####例子
public class Lx{ public static void main(String args[]){
int x = 30;
int y = 10;
if ( x == 30){
if( y == 10){
System.out.print("x = 30 and y = 10");
}
}
} } ```
作業(yè)練習(xí),建立一個(gè)數(shù)組,把元素從小到大排列
import java.util.Arrays;
public class Lx{public static void main(String[] args) {
int [] array = {2,8,1,9,5,4};
int temp; for (int i = 0; i < array.length; i++)
{ for (int j = 0; j < array.length;j++)
{ if (array[j] > array[i])
{ temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
for (int i = 0; i < array.length; i++)
{System.out.print(array[i]+" ");}
}} ```