三元条件运算符举例
-
格式化代码的快捷键ctrl+shift+f 自动导入:ctrl+shift+o
import java.util.Scanner;
public class Demo_1 {
public static void main(String[] args) {
// TODO Auto-generated method stubScanner input = new Scanner(System.in); System.out.println("请输入年份"); //if-else 分支结构--可以让程序有多条执行路径 if(input.hasNextInt()){ int year = input.nextInt(); if(year>0){ boolean isLeapYear = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0; System.out.println(year + "年" + (isLeapYear ? "是" : "不是") + "闰年"); input.close(); }else{ System.out.println("年份必须是正数"); } }else{ System.out.println("输入错误!"); } } }
分之结构if else举例
import java.util.Scanner;
public class Text3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("请输入x的值:");
double x = input.nextDouble();
double y;
if(x<-1){
y = 3 * x + 5;
}else if (x<=1) { //注意:else if表示已排除上面的条件了,既这里相当于x>=-1&&x<1
y = x - 1;
}else {
y = 5 * x - 3;
}
System.out.println("y= "+y);
input.close();
}