// LinearSearch.java: Search for a number in a list // from Liang's textbook import javax.swing.JOptionPane; public class LinearSearch { /** Main method */ public static void main(String[] args) { int[] list = new int[10]; // Declare and initialized output string String output = ""; // Create the list randomly and display it System.out.println("The list is "); for (int i =0; i < list.length; i++) { list[i] = (int)(Math.random() * 100); System.out.print(list[i] + " "); } // Prompt the user to enter a key String keyString = JOptionPane.showInputDialog(null, "Enter a key:", "Input", JOptionPane.QUESTION_MESSAGE); // Convert string into integer int key = Integer.parseInt(keyString); // Search for key int index = linearSearch(key, list); if (index != -1) System.out.println("\nThe key is found at subscript " + index); else System.out.println("\nThe key " + key + " is not found in the list"); System.exit(0); } /** The method for finding a key in the list */ public static int linearSearch(int key, int[] list) { for (int i = 0; i < list.length; i++) if (key == list[i]) return i; return -1; } }