Searching
// Contributed by - Anuj Das ( GC College, Silchar - @ Department of Computer Science )
import java.util.Scanner;
import java.util.ArrayList;
class FindNumber {
public static int searchNumber(ArrayList<Integer> list, int num) {
for(int i=0; i < list.size(); i++) {
if(list.get(i) == num) {
return (i+1);
}
}
return 0;
}
public static void main(String[ ] args) {
Scanner input = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<>();
System.out.print("Enter the size of Array: ");
int size = input.nextInt();
System.out.println("Enter "+size+" Elements: ");
for(int i=0; i < size; i++) {
list.add(input.nextInt());
}
// Displaying ArrayList
for(int i=0; i < list.size(); i++){
System.out.print(list.get(i)+" ");
}
System.out.print("\n");
System.out.print("Enter the number to be searched: ");
int num = input.nextInt();
if(searchNumber(list,num) == 0) {
System.out.println(num+" not found in this given ArrayList!!");
}
else {
System.out.println(num+" found at position: "+searchNumber(list,num));
}
}
}
OUTPUT
cmd-> javac FindNumber.java
cmd-> java FindNumber
Case - 1:
------------------------------------------------------------------
Enter the size of Array: 6
Enter 6 Elements:
45
65
22
58
74
22
45 65 22 58 74 22
Enter the number to be searched: 22
22 found at position: 3
Case - 2:
------------------------------------------------------------------
Enter the size of Array: 7
Enter 7 Elements:
45
21
87
98
54
66
12
45 21 87 98 54 66 12
Enter the number to be searched: 10
10 not found in this given ArrayList!!