如何用 Java 找出陣列中大於、小於或等於某個值的數字?


你可以按如下方式找出陣列中大於、小於或等於某個值的數字

示例

線上演示

public class GreaterOrLess {
   public static void main(String args[]) {
      int value = 65;
      int[] myArray = {41, 52, 63, 74, 85, 96 };
      System.out.println("Elements of the array that are equal to the given value are::");
      for(int i = 0; i<myArray.length; i++) {
         if(value==myArray[i]) {
            System.out.println("Index ::"+i+" Element::"+myArray[i]);
         }
      }
      System.out.println("Elements of the array that are greater than the given value are::");
      for(int i = 0; i<myArray.length; i++) {
         if(value<=myArray[i]) {
            System.out.println("Index ::"+i+" Element::"+myArray[i]);
         }
      }
      System.out.println("Elements of the array that are less than the given value are::");
      for(int i = 0; i<myArray.length; i++) {
         if(value>myArray[i]) {
            System.out.println("Index ::"+i+" Element::"+myArray[i]);
         }
      }
   }
}

輸出

Elements of the array that are equal to the given value are::
Elements of the array that are greater than the given value are::
Index ::3 Element::74
Index ::4 Element::85
Index ::5 Element::96
Elements of the array that are less than the given value are::
Index ::0 Element::41
Index ::1 Element::52
Index ::2 Element::63

更新於:2020 年 6 月 16 日

4K+ 次瀏覽

開啟您的職業生涯

透過完成課程獲得認證

入門
廣告