Java 程序检查数组是否包含给定值

javaobject oriented programmingprogramming更新于 2024/4/15 19:56:17

在本文中,我们将了解如何检查数组是否包含给定值。这是通过迭代数组元素并将给定的输入与数组元素进行比较来实现的。

下面是相同的演示 −

输入

假设我们的输入是 −

输入要搜索的数字:25
整数数组中的元素:
15 20 25 30 35

输出

所需的输出将是 −

数组包含给定的值

算法

步骤 1 - 开始
步骤 2 - 声明三个整数值,即 my_input 、i、array_size。定义一个布尔值 my_check 和一个整数数组 my_array
步骤 3 - 从用户处读取所需值/定义值
步骤 4 - 使用 for 循环迭代元素,并将给定输入的值与数组值进行比较。
步骤 5 - 如果值匹配,则元素存在。如果不匹配,则元素不存在。
步骤 6 - 显示结果
步骤 7 - 停止

示例 1

import java.util.Scanner;
public class Main {
   public static void main(String[] args) {
      int my_input , i, array_size;
      boolean my_check = false;
      System.out.println("Required packages have been imported");
      Scanner my_scanner = new Scanner(System.in);
      System.out.println("A reader object has been defined ");
      System.out.println("Enter the number to be searched ");
      my_input = my_scanner.nextInt();
      System.out.print("Enter the value of array_size : ");
      array_size = my_scanner.nextInt();
      int my_array[] = new int[array_size];
      System.out.println("Enter the elements of the array :" );
      for ( i = 0 ; i < array_size ; i++ ){
         my_array[i] = my_scanner.nextInt();
      }
      for ( i = 0 ; i < array_size ; i++ ) {
         if (my_array[i] == my_input) {
            my_check = true;
            break;
         }
      }
      if(my_check)
         System.out.println("\nThe array contains the given value");
      else
         System.out.println("\nThe array doesnot contain the given value");
   }
}

输出

Required packages have been imported
A reader object has been defined
Enter the number to be searched
25
Enter the size of array : 5
Enter the elements of the array :
10
15
20
25
30
The array contains the given value

示例 2

这里,整数已经被预先定义,并且它的值被访问并显示在控制台上。

public class Main {
   public static void main(String[] args) {
      int[] my_array = {15, 20, 25, 30, 35, 40};
      int my_input , i, array_size;
      array_size = 5;
      my_input = 25;
      boolean my_check = false;
      System.out.println("The number is defined as " +my_input);
      System.out.println("The elements in the integer array is defined as :" );
      for ( i = 0 ; i < array_size ; i++ ){
         System.out.print(my_array[i] +" ");
      }
      for ( i = 0 ; i < array_size ; i++ ) {
         if (my_array[i] == my_input) {
            my_check = true;
            break;
         }
      }
      if(my_check)
         System.out.println("\nThe array contains the given value");
      else
         System.out.println("\nThe array doesnot contain the given value");
   }
}

输出

The number is defined as 25
The elements in the integer array is defined as :
15 20 25 30 35
The array contains the given value

相关文章


有用资源