// purpose: demonstrate searching an array for a value import java.util.*; public class ArraySearch { public static void main( String[] args ) { // get a scanner for standard input Scanner stdin = new Scanner( System.in ); // determine the desired array size System.out.println(); System.out.print( "Enter number of elements: " ); int n = stdin.nextInt(); System.out.println(); // create the array int[] list = new int[ n ]; // put random integers between 0 .. 9 into the elements Random die = new Random(); for ( int i = 0; i < list.length; ++i ) { list[i] = die.nextInt( 10 ); } // display the array System.out.print( "list = " ); for ( int i = 0; i < list.length; ++i ) { System.out.print( list[ i ] + " " ); } System.out.println(); System.out.println(); // determine the search value System.out.print( "Enter search value: " ); int key = stdin.nextInt(); System.out.println(); // ************************ determine the index of the search value int index = -1; // assume its not there // examine list to see if its there for ( int i = 0; i < list.length; ++i ) { if ( key == list[ i ] ) { index = i; break; } } System.out.println( "index for " + key + ": " + index ); System.out.println(); } }