The following code is to perform the Linear Search on a list of 10 numbers. The list can be either sorted or unsorted.
Code:-
import java.util.*;
public class LinearSearch {
Scanner scan = new Scanner(System.in);
int i, search, list[] = new int[10];
public void input() {
try {
System.out.println("Enter 10 number list:-");
for (i = 0; i < 10; i++) {
list[i] = scan.nextInt();
}
System.out.printf("Search Number: ");
search = scan.nextInt();
} catch (InputMismatchException | NumberFormatException | ArrayIndexOutOfBoundsException | NullPointerException e) {
System.err.println("Error Occur\n" + e.getMessage());
System.exit(0);
}
}
public void compute() {
for (i = 0; i < 10; i++) {
if (list[i] == search) {
System.out.println("Number Found At Index: " + i);
break;
} else if (i == 10) {
System.out.println("Number Not Found In The List!");
}
}
}
public static void main(String[] args) {
LinearSearch bs = new LinearSearch();
bs.input();
bs.compute();
}
}
Output:-
Enter 10 number list:-
12
54
87
06
35
21
54
90
89
54
Search Number: 54
Number Found At Index: 1
Code:-
import java.util.*;
public class LinearSearch {
Scanner scan = new Scanner(System.in);
int i, search, list[] = new int[10];
public void input() {
try {
System.out.println("Enter 10 number list:-");
for (i = 0; i < 10; i++) {
list[i] = scan.nextInt();
}
System.out.printf("Search Number: ");
search = scan.nextInt();
} catch (InputMismatchException | NumberFormatException | ArrayIndexOutOfBoundsException | NullPointerException e) {
System.err.println("Error Occur\n" + e.getMessage());
System.exit(0);
}
}
public void compute() {
for (i = 0; i < 10; i++) {
if (list[i] == search) {
System.out.println("Number Found At Index: " + i);
break;
} else if (i == 10) {
System.out.println("Number Not Found In The List!");
}
}
}
public static void main(String[] args) {
LinearSearch bs = new LinearSearch();
bs.input();
bs.compute();
}
}
Output:-
Enter 10 number list:-
12
54
87
06
35
21
54
90
89
54
Search Number: 54
Number Found At Index: 1
Comments