/**
 * Demonstrate searching in an unordered array for an int.
 *
 * @author	Terry Sergeant
 * @version Case Study v1.0
*/
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.io.File;

public class WriteFile
{
	public static void main(String [] args) throws FileNotFoundException
	{
		Scanner kb= new Scanner(System.in);
		String [] names= new String[50];
		int i,n;

		n= loadNames(names);
		displayNames(names,n);

		System.out.println("Enter a name to add: ");
		names[n]= kb.nextLine();
		n++;

		displayNames(names,n);

		PrintStream outFile;

		outFile= new PrintStream(new File("out.txt"));

		for (i=0; i<n; i++)
			outFile.println(names[i]);

		outFile.close();
	}


	/**
	 * Loads names from a datafile into the given array.
	 *
	 * @param names an array to be filled with contents from data file.
	 * @return the number of values read from the file
	*/
	public static int loadNames(String [] names)
	{
		Scanner namefile;
		int n=0;

		try
		{
			namefile= new Scanner(new File("names.txt"));

			while (namefile.hasNextLine())
			{
				names[n]= namefile.nextLine();
				n++;
			}

			namefile.close();
		}
		catch (Exception e)
		{
			System.out.println(e);
		}

		return n;
	}


	/**
	 * Displays the first n numbers in the provided array.
	 *
	 * @param numbers an array of integers to be displayed
	 * @param n the number of values to be displayed
	*/
	public static void displayNames(String [] names, int n)
	{
		int i;

		System.out.println("Array has "+n+" values. Here they are: ");
		for (i=0; i<n; i++)
			System.out.println(names[i]);
	}
}
