条件语句(分支语句)
- if条件语句
public class TestIF {
public static void main(String[] args) {
int i = 20;
if(i < 20) {
System.out.println("<20");
} else if (i < 40) {
System.out.println("<40");
} else if (i < 60) {
System.out.println("i < 60");
} else
System.out.println("i <= 60");
//只有一句需要执行时可以省略{}
//但是只执行一句
}
}
- switch语句
public class TestSwitch {
public static void main(String[] args) {
int i = 18;
switch(i) {
case 8:
System.out.println("A");
break;
case 3:
System.out.println("B");
break;
case 2:
System.out.println("C");
break;
default:
System.out.println("error");
}
}
}
/*多个case合并:
case 8:
case 3:
case 2:
System.out.println("AA");
break;
*/
小心case穿透,使用break语句。
多个case可以合并到一起。
java中switch语句只能探测int类型值(char,byte,short可以转换为int)。
循环语句
- for循环语句
//for 语句形式
/*
for(表达式1;表达式2;表达式3) {
语句;
...;
语句;
}
*/
例:计算1+3+5+…+99?
public class TestOddSum {
public static void main(String[] args) {
int result = 0;
for (int i=1;i<100;i+=2) {
result += i;
}
System.out.println("result=" + result);
}
}
- while,do while语句
public class TestWhile {
public static void main(String[] args) {
int i = 0;
while(i < 10) {
System.out.println(i);
i++;
} //0~9
i = 0; //int i = 0不可
do {
i++;
System.out.println(i);
} while(i < 10); //1~10不能忘记分号
i = 0;
do {
System.out.println(i);
i++;
} while(i < 10); //0~9
}
}
break,continue语句
- break语句:终止某个语句块的执行,用在循环语句体中可强制退出循环。(终止break所在的一层循环)
public class TestBreak {
public static void main(String[] args) {
int stop = 4;
for(int i=1;i<=10;i++) {
//当i等于4时退出循环
if(i == stop) break;
System.out.println("i=" + i);
}
}
}
- continue语句:用在循环语句体中用于终止某次循环过程,跳过循环体中continue下面未执行的循环,开始下一次循环。
public class TestContinue {
public static void main(String[] args) {
int skip = 4;
for(int i = 1;i<=5;i++) {
//当i等于skip时,跳过当次循环
if(i == skip) continue; //if(i == skip);continue;
System.out.println("i=" + i); //System.out.println(i);永远不能执行到此句
}
}
}