/**
 * DAC MAD Q1: Basics of Programming: Android (ART - 40544)
 * 
 * @author Antti Myllykoski, October 11, 2013.
 * 
 *         Homework Week 3. Find a number from an array.
 */

import java.util.InputMismatchException;
import java.util.Random;
import java.util.Scanner;

public class ArrayFindNum {

	private static final int ARRAY_SIZE = 100;
	private static final String FOUND = "We found your number %s at position %s in the array.\n";

	public static void main(String[] args) {
		searchForNumbers(createArray());
	}

	/**
	 * Searches an array with randomly generated integers for number(s) entered
	 * by the user.
	 * 
	 * @param numbers
	 *            array of random numbers (1..ARRAY_SIZE)
	 */
	private static void searchForNumbers(int[] numbers) {
		Scanner scanner = new Scanner(System.in);
		int userInput = 1;
		while (true) {
			System.out.println("Give a number between 1-100 (0 to quit).");
			try {
				if ((userInput = scanner.nextInt()) == 0)
					break;
				searchArrayForNumber(numbers, userInput);
			} catch (InputMismatchException e) {
				System.out.println("Please give a valid number.");
				scanner.next(); // Clears the scanner buffer from crap
			}
		}
		System.out.println("Finished.");
	}

	/**
	 * Performs a brute force search to find the given number from the array.
	 * 
	 * @param numbers
	 *            the array
	 * @param what
	 *            user's number
	 */
	private static void searchArrayForNumber(int[] numbers, int what) {
		for (int i = 0; i < numbers.length; i++)
			if (numbers[i] == what) {
				System.out.printf(FOUND, what, i);
				return;
			}
		System.out.println("No match was found.");
	}

	/**
	 * Creates an array with randomly generated numbers.
	 * 
	 * @return array populated with random numbers
	 */
	private static int[] createArray() {
		int[] numbers = new int[ARRAY_SIZE];
		Random rnd = new Random();
		for (int i = 0; i < numbers.length; i++)
			numbers[i] = rnd.nextInt(ARRAY_SIZE) + 1;
		return numbers;
	}
}
