if語句:
if(比較表達式1) {
語句體1;
}else if(比較表達式2) {
語句體2;
}else if(比較表達式3) {
語句體3;
}
...
else {
語句體n+1;
}
2.if的嵌套public static void main(String[] args) {
/*比較三個數中的最大值
使用if的嵌套
else總是與最近的一個if相匹配
*/
int a= 54;
int b = 34;
int c = 77;
if (a>b){
if (a>c){
System.out.println("最大值是:"+a);
}else{
System.out.println("最大值是:"+c);
}
}else{//b>=a
if(b>c){
System.out.println("最大值是"+b);
}else{
System.out.println("最大值是"+c);
}
}
Switch語句:
switch(表達式){
case 值1:
語句體1;
break;
case 值2:
語句體2;
break;
.....
defult:
語句體n+1;
break;
}
注意事項:沒有break,可能會出現case穿透,例:int x = 2;
int y = 3;
switch(x){
default:
y++;
case 3:
y++;
case 4:
y++;
}
System.out.println("y="+y);//輸出結果爲6
總結:switch和if的使用場景
* switch:判斷固定值的時候使用
* if:判斷某個範圍或者區間時使用
循環結構for,while,do...while語句的格式:
for(初始化表達式;條件表達式;循環後的操作表達式) {
循環體;
}
初始化語句;
while(判斷條件語句) {
循環體語句;
控制條件語句;
}
初始化語句;
do {
循環體語句;
控制條件語句;
}while(判斷條件語句);
* while(true){...}
* for(;;){...}
循環結構案例1:
public static void main(String[] args) {
// 打印4行5列的星星
for(int i = 1;i<=4;i++){
for(int j = 1;j<=4;j++){
System.out.print("*");
}
System.out.println();
}
外循環控制行數,內循環控制列數
循環結構案例2:
public static void main(String[] args) {
// 打印九九乘法表
/*1*1=1
*1*2=2 2*2=4
*1*3=3 2*3=6 3*3=9
*1*4=4 2*4=8 3*4=6 4*4=16
* ...
* 1*9=9 2*9=18 ... 9*9=81
*
*
* */
for(int i=1;i<=9;i++){
for(int j=1;j<=i;j++){
System.out.print(j+"*"+i+"="+(i*j)+"\t");
}
System.out.println();
}
}
控制跳轉語句break和continue的區別:
public static void main(String[] args) {
// break只能用在switch和循環裏;跳出循環
//continue只能用在循環中;終止本次循環,繼續下次循環
for(int x = 1;x<= 5 ;x++){
if(x==4){
break;
}
System.out.println(x);//1 2 3
}
for(int x = 1;x<= 5 ;x++){
if(x==4){
continue;
}
System.out.println(x);//1 2 3 5
}
}
2018-1-26 於家中