Day11_30

三元條件運算符舉例

  • 格式化代碼的快捷鍵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 stub

      Scanner 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();
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容