import java .util.Scanner;// 导入包
public class Demo_4 {
// 主方法
public static void main(String[] args) {
/*
* if 条件分支语句
* 语法: if (条件表达式){代码} 条件表达式:结果只有两种【true/false
* boolean 类型】,如果结果为true才会执行if中代码 3>2: true
*
* if else 双条件分支语句
* 语法: if(条件表达式){ if条件表达式成立的时候要执行的代码 }else{
* if不条件表达式成立的时候要执行的代码 }
* eg:比较两个数的大小,输出最大的那个数
* if(a>b){
* System.out.println("max = " + a); }
* else{ System.out.println("max = "+ b); }
*
* 多条件分支语句:
* eg:学生成绩等级
* [90 -100] A
* [80 - 90) B
* [70 - 80) C
* [60 - 70) D
* <60 E
* 定义一个变量score = 23
* 如果 score>=90 &&【并且】score<=100
* A
* else if score>=80 && score <90
* B
* else if score>=70 && score<80
* C
* else if score>=60 && score<70
* D
* else
* E
*/if (3 > 2) {
System.out.println("if 条件表达式成立的时候才会执行if中的代码");
}
if (3 < 2) {// false
System.out.println("if 条件表达式成立的时候才会执行if中的代码..........");
} else {
System.out.println("if 条件表达式不成立的时候才会执行else中的代码");
}
// 比较两个数的大小,输出最大的那个数
// 定义两个变量 a,b
int a = 1;
int b = 2;
if (a > b) {
System.out.println("max = " + a);
} else {
System.out.println("max = " + b);
}
/* 另一写法: 运算符 》条件运算符也叫三目运算符等价于if()else
* 语法:
* 表达式1?表达式2:表达式3;
* 表达式1:结果为boolean类型【true/false】 a>b
* 如果表达式1的结果为true,则执行表达式2,否则执行表达式3
* 如果a>b ,执行max=a,否则max=b
* */int max = (a>b)?a:b;
System.out.println("max = " + max);
/* 学生成绩评定
* 学生成绩通过用户输入【获取键盘输入的值】,借助java中一个类Scanner,
* 必须创建这个类的实例对象,可以通过这个具体实例对象访问【调用】这个类中的方法
* */Scanner sc = new Scanner(System.in);
System.out.println("请输入学生的成绩:");
int score ;// 只是定义变量score 不赋值
if(sc.hasNextInt()){// hasNextInt()这个方法用来判断用户键盘输入的值是不是一个数字【int类型】
score = sc.nextInt();// 这个nextInt()方法就是获取键盘输入的int类型的值
if(score>=90&&score<=100){
System.out.println("A");
}
else if(score>=80&&score<90){
System.out.println("B");
}
else if(score>=70&&score<80){
System.out.println("C");
}
else if(score>=60&&score<70){
System.out.println("D");
}
else{
System.out.println("不及格!");
}
}else{
System.out.println("用户输入的不是一个数字!!");
}
}
}
文章来源:智云一二三科技
文章标题:Java入门 条件分支语句
文章地址:https://www.zhihuclub.com/195273.shtml