if else條件語句


Java 條件語句

  • if
  • if…else
  • if…else if…else
  • if…else嵌套

if

語法格式:

if(表達式){
    //如果表達式結果位true 那么執行這里的代碼
}

示例

public class Test { public static void main(String args[]){ int x = 10; if( x < 20 ){ System.out.print("這是 if 語句"); } } } 

 

if…else

語法格式:

if(布爾表達式){
    //true
}else{
    //false
}

示例

public class Test { public static void main(String args[]){ int x = 30; if( x < 20 ){ System.out.print("這是 if 語句"); }else{ System.out.print("這是 else 語句"); } } } 


if…else if…else

 


語法格式:

if(布爾表達式 1){
   //如果布爾表達式 1的值為true執行代碼
}else if(布爾表達式 2){
   //如果布爾表達式 2的值為true執行代碼
}else if(布爾表達式 3){
   //如果布爾表達式 3的值為true執行代碼
}else {
   //如果以上布爾表達式都不為true執行代碼
}

注意:

  1. 最多有一個else語句
  2. 可以有若干個else if語句,但必須再else之前
  3. 一旦其中一個else if語句檢測為true,其他的else if以及else都會被跳過。

示例

public class Test { public static void main(String args[]){ int x = 30; if( x == 10 ){ System.out.print("Value of X is 10"); }else if( x == 20 ){ System.out.print("Value of X is 20"); }else if( x == 30 ){ System.out.print("Value of X is 30"); }else{ System.out.print("這是 else 語句"); } } } 

 

if…else嵌套

語法格式:

if(布爾表達式 1){
   ////如果布爾表達式 1的值為true執行代碼
   if(布爾表達式 2){
      ////如果布爾表達式 2的值為true執行代碼
   }
}

示例

public class Test { public static void main(String args[]){ int x = 30; int y = 10; if( x == 30 ){ if( y == 10 ){ System.out.print("X = 30 and Y = 10"); } } } } 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM