三元條件運算符舉例
-
格式化代碼的快捷鍵ctrl+shift+f 自動導(dǎo)入: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 分支結(jié)構(gòu)--可以讓程序有多條執(zhí)行路徑 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("年份必須是正數(shù)"); } }else{ System.out.println("輸入錯誤踩身!"); } } }
分之結(jié)構(gòu)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表示已排除上面的條件了社露,既這里相當(dāng)于x>=-1&&x<1
y = x - 1;
}else {
y = 5 * x - 3;
}
System.out.println("y= "+y);
input.close();
}