1.if条件语句
格式:
- if
- if… else…
- if… else if …
- if… else if … else if …
- if… else if … else if … else …
public class TestIF {
public static void main(String[] args) {
int i = 20;
if(i < 20) {
System.out.println("<20");
System.out.println("<20");
} else if (i < 40) {
System.out.println("<40");
} else if (i < 60) {
System.out.println("<60");
} else
System.out.println(">=60"); //单行可以省略大括号(建议不要省)
System.out.println(">=60");
}
}
2.switch条件语句
格式:
switch(){
case xx:
...;
case xx:
...;
default:
...
}
注意:
-
case后面只能是常量,不能是变量,而且多个case后面的值不能相同;
-
default语句表示所有情况都不匹配的时候,执行的内容,可以省略,但不建议,它的作用是让代码更健壮;
-
break可以分情况省略,省略之后会有case穿透现象;
-
default不一定要放在最后,可以放在任意位置;
-
switch语句结束的条件:遇到break或者执行到末尾;
public class TestSwitch {
public static void main(String[] args) {
int i = 2;
switch(i) {
case 2 :
System.out.println("C");
break;
case 9 :
System.out.println("D");
break;
default:
System.out.println("error");
}
}
}
3.for循环语句
格式:
for(初始化表达式语句;判断条件语句;控制条件语句) {
循环体语句;
}
执行流程:执行初始化表达式语句——>执行判断条件语句,看其返回值是true还是false——>是ture就继续执行,是false就结束循环——>执行循环体语句;——>执行控制条件语句——>回到第二句继续;
例:计算1+3+5+…+99
public class OddSum {
public static void main(String[] args) {
long result = 0;
for(int i=1; i<=99; i+=2) {
result += i;
}
System.out.println("result=" + result);
}
}
4.while & do while循环语句
格式:
- while(逻辑表达式)…
- do{语句;…;}while(逻辑表达式);
public class TestWhile {
public static void main(String[] args) {
int i = 0;
while(i < 10) {
System.out.println(i);
i++;
}
i = 0;//声明变量只用一次(不用再int i = 0)
do {
i++;
System.out.println(i);
} while(i < 10);
}
}
5.break & continue语句
- break语句用于终止某个语句块的执行。
用在循环语句体中,可以强行退出循环。 - continue语句用在循环语句体重,用于终止某次循环过程,跳过循环体中continue语句下面未执行的循环,开始下一次循环
public class TestBreak
{
public static void main(String[] args)
{
int stop = 4;
for(int i = 1;i <= 5;i++){
if (i == stop) break; //退出循环
System.out.println("i=" + i);
}
//i=1 i=2 i=3
int skip = 4;
for(int j = 1;j <= 5;j++){
if (j == skip) continue; //跳过当次循环
System.out.println("j=" + j);
}
//i=1 i=2 i=3 i=5
}
}
6.练习
例:输出1~100内前5个可以被3整除的数
//while语句
public class Test01 {
public static void main(String[] args) {
int i = 1,j = 0;
while(i < 100){
if(i % 3 == 0){
System.out.println("i=" + i);
j++;
}
if(j == 5) break;
i++;
}
}
}
//for语句
public class Test02 {
public static void main(String[] args) {
int j = 0;
for(int i = 1;i < 100;i++){
if(i % 3 == 0){
System.out.println("i=" + i);
j++;
}
if(j == 5) break;
}
}
}
例:输出101~200内的质数
public class Test03 {
public static void main(String[] args){
for(int i = 101;i < 200;i += 1){
boolean f = true;
for (int j = 2;j < i;j++){
if (i % j == 0 ){
f = false;
break;
}
}
if(!f){
continue;
}
System.out.println(i);
}
}
}