이 기사에서는 배열에 주어진 값이 포함되어 있는지 확인하는 방법을 이해할 것입니다. 이것은 배열 요소를 반복하고 주어진 입력을 배열 요소와 비교하여 수행됩니다.
아래는 동일한 데모입니다 -
입력
입력이 -
라고 가정합니다.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