在Java中查詢陣列中存在0或任何負整數元素的索引


根據題意,我們得到一個包含一些隨機整數值的陣列,我們必須找出並列印包含任何零或負值的索引。

注意 - 使用整數陣列

讓我們深入研究這篇文章,瞭解如何使用Java程式語言來實現它。

為了向您展示一些例項

例項1

給定陣列 = [1, 2, -3, -4, 0, 5]

包含零和負值的索引 = 2, 3, 4

例項2

給定陣列 = [-1, 0, 4, 6, 8, -5]

包含零和負值的索引 = 0, 1, 5

例項3

給定陣列 = [-2, 3, -9, 12, 0, -7]

包含零和負值的索引 = 0, 2, 4, 5

演算法

步驟1 − 使用靜態輸入方法宣告一個包含一些隨機整數值的陣列。

步驟2 − 使用for迴圈迭代所有元素,並在每次迭代中檢查零或負值。

步驟3 − 如果我們得到任何零值或負值,我們列印該索引號作為輸出。

步驟4 − 如果在陣列中沒有找到任何零或負值,則我們列印“N/A”。

語法

要獲取陣列的長度(陣列中元素的數量),陣列有一個內建屬性,即length

以下是它的語法:

array.length

其中,'array' 指的是陣列引用。

多種方法

我們提供了不同的方法來解決這個問題。

  • 使用靜態輸入方法

  • 使用使用者自定義方法

讓我們逐一檢視程式及其輸出。

方法1:使用靜態輸入方法

在這種方法中,我們宣告一個包含一些隨機整數值的陣列,並使用我們的演算法查詢零和負值,並將相應的索引號作為輸出列印。

示例

import java.util.*;
public class Main {
   public static void main(String[] args){
      
      // declare an integer type of array and store some random value to it by static input method
      int[] inputArray = {-34, 25, 7, 0, 9};
      
      //declare a integer variable to store the count value
      int count=0;
      
      //print the output
      System.out.print("The indexes which contain Zero and negative values = ");
      
      //initiate the loop to find the indexes
      for(int i=0; i< inputArray.length; i++){
         if(inputArray[i] <= 0){
            
            // Print the indexes
            count+=1;
            System.out.print(i+" ");
         }
      } 
      
      //if the array doesn't contain any zro or negative values
      if(count==0)
      System.out.print("The array does not contain any negative or 0 value");
   }
}

輸出

The indexes which contain Zero and negative values = 0 3

方法2:使用使用者自定義方法

在這種方法中,我們宣告一個包含一些隨機整數值的陣列,並將該陣列作為引數傳遞給我們的使用者自定義方法,在使用者自定義方法中使用該演算法,我們找到包含零或負值的索引,並將這些索引值作為輸出列印。

示例

import java.util.*;
public class Main {
   public static void main(String[] args){
      
      // declare an integer type array and initialize it
      int[] inputArray = { -34, 0, 25, -67 , 87};
      // call the user-defined method and pass the inputArray[]
      printIndex(inputArray);
   }
   //user-defined method to print the indexes which contains zero or negative values
   static void printIndex(int[] inpArr){
      int count=0;
      //print the output
      System.out.print("The index contains Zero and negative values = ");
      //take a for loop to iterate and find the indexes
      for(int i=0; i< inpArr.length; i++){
         if(inpArr[i]<=0){
            // Print the array as output
            count+=1;
            System.out.print(i+" ");
         }
      } 
            
      //print if the array doesn't contain any zro or negative values
      if(count==0)
      System.out.print(" N/A");
   }
}

輸出

The index contains Zero and negative values = 0 1 3

在這篇文章中,我們探討了使用Java程式語言查詢0或任何負元素索引的不同方法。

更新於:2023年3月6日

678 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.