//三元表达式的嵌套
int max = i > j ? (i > k ? i : k) : (j > k ? j : k);
//练习:输出分数所对应的等级 >=90 -A >=80 -B >=70 -C >=60 -D <60 -E
char level = score >= 90 ? 'A':(score >= 80 ? 'B' : (score >= 70 ? 'C' : (score >=60 ? 'D' : 'E')));
System.out.println(level);
扩展:从控制台获取数据
import java.util.Scanner;
Scanner s = new Scanner(System.in);
int i = s.netInt(); //获取整数
double d = s.nextDouble(); //获取小数
String str = s.next();
>= 大于等于 >>= 右移等于
10 >= 2 -> true
10 >>= 2 ->i = i >> 2; -> 2
运算符的优先级
~! 算术(++ -- * / % + - ) <> >>> 关系 逻辑& | ^ 三元 赋值
一元 二元运算
(一元的几个运算符的优先级是一样的)
流程控制
顺序结构:指代码从上到下从左到右来依次编译运行的
分支结构:
判断结构
if(逻辑值){
代码块
}
执行顺序:先执行逻辑值,如果逻辑值为 true,那么执行 代码块。
注意:如果 if 中的代码块只有 1 句话,那么可以省略 {} 不写
if(逻辑值){
Code1;
}else{
Code2;
}
练习:
1.输入三个数字,获取三个数字中的最小值
import java.util.Scanner;
public class IfElseExer {
public static void main(String[] args){
Scanner s = new Scanner(System.in);
int i = s.nextInt();
int j = s.nextInt();
int k = s.nextInt();
/*
if(i < j){
if(i < k){
System.out.println(i);
} else {
System.out.println(k);
}
} else {
if(j < k){
System.out.println(j);
} else {
System.out.println(k);
}
}
*/
int min = i;
if(min > j)
min = j;
if(min > k)
min = k;
System.out.println(min);
}
}
2.输入一个数字表示重量,如果重量<=20,则每千克收费 0.35 元;如果超过 20 千克不超过 100 千克的范围,则超过的部分按照每千克 0.5 元收费;如果超过 100 千克,则超过的范围按照每千克 0.8 元收费。
import java.util.Scanner;
public class IfElseExer2 {
public static void main(String[] args){
Scanner s = new Scanner(System.in);
double weight = s.nextDouble();
double price = 0;
if(weight < 0){
System.out.println("不合法的重量!!!");
} else {
if(weight <= 20){
price = weight * 0.35;
} else {
if(weight <= 100){
price = 20 * 0.35 + (weight - 20) * 0.5;
} else {
price = 20 * 0.35 + 80 * 0.5 + (weight - 100) * 0.8;
}
}
}
System.out.println(price);
}
}
或者
import java.util.Scanner;
public class IfElseIfDemo {
public static void main(String[] args){
Scanner s = new Scanner(System.in);
double weight = s.nextDouble();
double price = 0;
if(weight < 0){
System.out.println("非法的重量!!!");
} else if(weight <= 20){
price = weight * 0.35;
} else if(weight <= 100){
price = 7 + (weight - 20) * 0.5;
} else {
price = 47 + (weight - 100) * 0.8;
}
System.out.println(price);
}
}
if(逻辑值1){
Code1;
}else if(逻辑值2){
Code2;
}
练习:
输入一个数字表示月份,然后输出这个月份所对应的季节。 3 - 5 -春 6 - 8 - 夏 9 - 11 - 秋 12、1、2 - 冬
import java.util.Scanner;
public class IfElseIfExer {
public static void main(String[] args){
Scanner s = new Scanner(System.in);
int month = s.nextInt();
if(month < 1 || month > 12){
System.out.println("Illegal month !!!");
} else if(month > 2 && month < 6){
System.out.println("Spring");
} else if(month > 5 && month < 9){
System.out.println("Summmer");
} else if(month > 8 && month < 12){
System.out.println("Autumn");
} else {
System.out.println("Winter");
}
}
}
选择结构
循环结构: