选择控制语句
- if else
if选择结构是根据条件判断之后再做处理
if ( 条件 ) {
//代码块
} - if…else if…else 结构
语法
if(布尔表达式 1){
//如果布尔表达式 1的值为true执行代码
}else if(布尔表达式 2){
//如果布尔表达式 2的值为true执行代码
}else if(布尔表达式 3){
//如果布尔表达式 3的值为true执行代码
}else {
//如果以上布尔表达式都不为true执行代码
} - 嵌套if
使用嵌套的 if…else 语句是合法的。也就是说你可以在另一个 if 或者 else if 语句中使用 if 或者 else if 语句。
语法:
if(布尔表达式 1){
如果布尔表达式 1的值为true执行代码
if(布尔表达式 2){
如果布尔表达式 2的值为true执行代码
}
}
如以下实例
package com.lpl.demo;
import java.util.Scanner;
public class hello3 {
public static void main(String [] arge){
//创建sc对象
Scanner sc=new Scanner(System.in);
System.out.println("张三的成绩是:");
int score=sc.nextInt();//获取用户控制台输入的整数
if(score>90){
if(score>=95){
System.out.println("奖励1000元");
}else{
System.out.println("非常好,奖励一个MP4");
}
}else if(score>=60&&score<90){
System.out.println("优秀!再接再厉");
}else if(score>=50&&score<60){
System.out.println("不及格,努力吧");
}else{
System.out.println("非常不好,叫家长!");
}
}
}
循环控制语句
- while(特点:先判断,再执行)
while是最基本的循环,它的结构为:
while( 布尔表达式 ) {
//循环内容
}
public class Test {
public static void main(String args[]) {
int x = 10;
while( x < 20 ) {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
}
}
- 2.do while(特点:先执行,再判断)
do…while 循环和 while 循环相似,不同的是,do…while 循环至少会执行一次。
do…while 循环的结构如下:
do {
//代码语句
}while(布尔表达式);
public class Test {
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 );
}
}
- For(非常重要)(特点:先判断,再执行)
例如,输出100次“好好学习!”
使用while循环结构:
int i=0;
while(i<100){
System.out.println("好好学习!");
i++;
}
使用for循环结构:
for(int i=0;i<100;i++){
System.out.println("好好学习!");
}
- break和continue
break用于do-while、while、for中时,可跳出循环而执行循环后面的语句
continue 适用于任何循环控制结构中。作用是跳过循环体中剩余的语句而执行下一次循环。