ในบทความนี้ เราจะเข้าใจวิธีการตรวจสอบว่าอาร์เรย์มีค่าที่กำหนดหรือไม่ สิ่งนี้ทำได้โดยการวนซ้ำองค์ประกอบอาร์เรย์และเปรียบเทียบอินพุตที่กำหนดกับองค์ประกอบอาร์เรย์
ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน -
ป้อนข้อมูล
สมมติว่าข้อมูลที่เราป้อนคือ −
Enter the number to be searched: 25 The elements in the integer array: 15 20 25 30 35
ผลผลิต
ผลลัพธ์ที่ต้องการจะเป็น −
The array contains the given value
อัลกอริทึม
Step 1 - START Step 2 - Declare three integer values namely my_input , i, array_size. A Boolean value my_check is defined and an integer array my_array is defined Step 3 - Read the required values from the user/ define the values Step 4 - Iterate the elements using a for loop and compare the values of the given input with in array values. Step 5 - If the values match, the element is present. If not, the element is not present. Step 6 - Display the result Step 7 - Stop
ตัวอย่างที่ 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