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或任何负数元素的方法。