Java程式檢查數字是正數還是負數


在本文中,我們將學習如何在Java中檢查數字是正數還是負數。要檢查指定的數字是正數還是負數,可以參考0。大於0的數字被認為是正數,而小於0的數字被認為是負數,我們可以使用Java條件語句,如if-else-if塊或三元運算子。在此之前,讓我們藉助示例討論問題陳述:

問題陳述

給定一個整數作為輸入,編寫一個Java程式來檢查該數字是正數還是負數。

輸入1

num = -30

輸出1

res = -30 is a negative number

輸入2

num = 35

輸出2

res = 35 is a positive number

不同的方法

以下是檢查數字是正數還是負數的不同方法。

使用if else if塊

在這種方法中,我們將使用if-else-if塊,它允許我們傳遞多個條件,並且只執行為真的語句。

示例

在下面的Java程式中,我們將使用if-else塊來檢查給定的整數變數是正數還是負數。

public class Example1 {
   public static void main(String[] args) {
      int myInput = 788;
      System.out.println("The given number is: " + myInput);
      // to check given number is positive or negative
      if(myInput > 0) {
         System.out.println(myInput + " is a positive number");
      } else if(myInput == 0) {
         System.out.println(myInput + " is equal to zero");
      } else {
         System.out.println(myInput + " is a negative number");
      }
   }
}

輸出

The given number is: 788
788 is a positive number

使用三元運算子

在Java中,三元運算子可以在某些情況下用作if-else條件的替代方案。三元運算子通常稱為條件運算子,它包含三個運算元。透過使用它,我們可以確定指定的變數是正數還是負數。

示例

下面的Java程式演示了三元運算子在檢查數字是正數還是負數時的實際實現。

public class Example2 {
   public static void main(String[] args) {
      int myInput = 788;
      System.out.println("The given number is: " + myInput);
      // to check given number is positive or negative
      boolean isGreater = (myInput > 0) ? true : false;
      if(isGreater) {
         System.out.println(myInput + " is a positive number");
      } else {
         System.out.println(myInput + " is a negative number");
      }
   }
}

輸出

The given number is: 788
788 is a positive number

結論

在本文中,我們學習了正數和負數,以及如何識別給定數字是否為正數。為了執行此操作,我們編寫了兩個不同的Java程式,它們分別使用if else if塊和三元運算子。三元運算子if else if條件塊最有效的替代方案。

更新於: 2024年9月13日

836 次檢視

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.