Java中检查数组是否不包含0和负数


在Java中,数组是一个对象。它是一种非原始数据类型,用于存储相同数据类型的多个值。

根据题目要求,我们需要检查并确认数组中不包含0和负数。如果数组包含0或负数元素,则结果应显示“数组包含0或负数”。否则,结果应为“数组不包含0或负数”。

注意 - 数组必须是整数数组。

让我们通过这篇文章来了解如何使用Java编程语言来实现这一点。

展示一些示例

示例1

Suppose the original array is {4, 0, 3, 1, 8, 5, 9}

在检查数组中是否存在0或负数元素后,结果将是:

数组包含0或负数。

示例2

Suppose the original array is {4, 3, -6, 1, 8, 11, 9}

在检查数组中是否存在0或负数元素后,结果将是:

数组包含0或负数。

示例3

Suppose the original array is {4, 24, 3, 1, 18, 51, 9}

在检查数组中是否存在0或负数元素后,结果将是:

数组不包含0或负数。

算法

  • 步骤1 - 声明并初始化一个整数数组。

  • 步骤2 - 设置布尔标志 flag = false;

  • 步骤3 - 使用条件“if(arr[i] <= 0)”检查是否存在任何负数或0。

  • 步骤4 - 如果步骤3为真,则将“flag = true”

  • 步骤5 - 打印 数组包含0或负数。

  • 步骤6 - 否则打印 数组不包含0或负数。

语法

要获取数组的长度(数组中元素的数量),数组有一个内置属性,即length

以下是它的语法:

array.length

其中,'array' 指的是数组引用。

多种方法

我们提供了多种解决方案。

  • 使用静态数组初始化

  • 使用用户自定义方法

让我们逐一查看程序及其输出。

方法1:使用静态数组初始化

示例

在这种方法中,数组元素将在程序中初始化。然后根据算法检查并确认数组中不包含0和负数。

public class Main{
   //main method
   public static void main(String[] args) {
   
      //Declare and initialize the array elements
      int arr[] = { 4, 3, -6, 1, 8, 11, 9 };
      
      //declare boolean to check for negative or 0
      boolean flag = false;
      
      // check is there any negative numbers or 0
      for (int i = 0; i < arr.length; i++) {
         if(arr[i] <= 0){
            flag = true;
            break;
         }
      }
      
      // -ve or 0 number is not available
      if(!flag) {
         System.out.println("Array does not contain 0 or a negative number.");
         return;
      }
      
      // -ve or 0 number is available
      else
         System.out.println("Array contain 0 or a negative number.");   
   }
}

输出

Array contain 0 or a negative number.

方法2:使用用户自定义方法

示例

在这种方法中,数组元素将在程序中初始化。然后通过将数组作为参数调用用户自定义方法,并在方法内部根据算法检查并确认数组中不包含0和负数。

public class Main{
    //main method
   public static void main(String[] args){
   
      //Declare and initialize the array elements
      int arr[] = { 4, 24, 3, 1, 18, 51, 9 };
      
      //calling a user defined method
      check(arr);
   }
   
   //user defined method
   public static void check(int []arr){
   
      //declare boolean to check for negative or 0
      boolean flag = false;
      
      // check is there any negative numbers or 0
      for (int i = 0; i < arr.length; i++) {
         if(arr[i] <= 0){
            flag = true;
            break;
         }
      }
      
      // -ve or 0 number is not available
      if(!flag) {
         System.out.println("Array do not contain 0 or a negative number.");
         return;
      }
      
      // -ve or 0 number is available
      else
         System.out.println("Array contain 0 or a negative number.");   
   }
}

输出

Array do not contain 0 or a negative number.

在这篇文章中,我们探讨了如何在Java中检查并确认数组中不包含0和负数。

更新于:2023年1月5日

2K+ 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.