import java.io.*;
import java.util.Scanner;

/**
 * This program demonstrates file and console I/O in Java.
 * 
 * @author Beck Hasti, copyright 2005-8, all rights reserved
 */
public class PlanetIO {

    public static void main(String args[]) throws IOException {
        final int NUM_PLANETS = 9;  // Note: here we are assuming Pluto is
	                            // (or will be again) a planet
        final String FILE_NAME = "planets.txt";
        int i;
        String[] planetOut = new String[NUM_PLANETS];
        String[] planetIn = new String[NUM_PLANETS];
        int[] moonsOut = new int[NUM_PLANETS];
        int[] moonsIn = new int[NUM_PLANETS];

        //////////////////////////////////////////////////////////
        // read the planet and moon information from the console
        //////////////////////////////////////////////////////////

        System.out.println("You will be prompted to enter " + NUM_PLANETS
                           + " planets and # of moons for each planet");
        
        Scanner stdin = new Scanner(System.in);

        for (i = 0; i < NUM_PLANETS; i++) {

            System.out.print("Name of planet " + (i + 1) + ": ");
            planetOut[i] = stdin.nextLine();

            System.out.print("Number of moons: ");
            try {
                moonsOut[i] = Integer.parseInt(stdin.nextLine());
            } catch (NumberFormatException nfe) {
                // If the user enters a non-integer, we will just print an error
                // message and assign the number of moons a default value.
                // A better approach (left to the student to implement) would be
                // to print an error message and allow the user to re-enter the
                // value (and continue to allow the user to re-enter a value  
                // until it is an integer). Note also that we are not checking 
                // for the "reasonable-ness" of the value entered by the user, 
                // e.g., we accept -12345 as a valid number of moons.

                // Here we use System.err to print out the error message. We
                // could also have used System.out  Eclipse prints both 
                // System.out and System.err to the console window; it uses 
                // blue font for System.out and red font for System.err
                // Other environments may handle print messages sent to
                // System.err differently.
                System.err.println("Error: non-integer entered, "
                        + "will use -1 instead");
                moonsOut[i] = -1;
            }
        }

        //////////////////////////////////////////////////////////
        // print the planet and moon information to a file
        //////////////////////////////////////////////////////////
        
        File dstFile = new File(FILE_NAME);

        if (dstFile.exists()) {
            System.out.println("Warning: File " + FILE_NAME + " already exists "
                    + " - file will be overwritten");
        }

        if (dstFile.isDirectory() || 
	      (dstFile.exists() && !dstFile.canWrite())) {
            System.out.println("ERROR: File " + FILE_NAME + " not writeable");
            System.exit(1);
        }
        
        // Creates a a PrintStream attached to the given File object.
        // This will overwrite the existing file and does not provide
        // auto-flushing.
        PrintStream outFile = new PrintStream(dstFile);

        for (i = 0; i < NUM_PLANETS; i++) {
            outFile.println(planetOut[i] + ":" + moonsOut[i] + ":");
            outFile.flush();  // flush output from buffer to file
        }
        outFile.close();  // close the file (also flushes the buffer)
        System.out.println("Planet and moon info written to file "
        		           + FILE_NAME);

        //////////////////////////////////////////////////////////
        // read the planet and moon information from a file
        //////////////////////////////////////////////////////////
        
        System.out.println("About to read planet and moon info from file "
        		           + FILE_NAME);
        File srcFile = new File(FILE_NAME);

        if (!srcFile.exists()) {
            System.out.println("ERROR: File " + FILE_NAME + " not found");
            System.exit(1);
        }

        else if (!srcFile.isFile() || !srcFile.canRead()) {
            System.out.println("ERROR: File " + FILE_NAME + " not readable");
            System.exit(1);
        }

        // create a scanner from the file
        Scanner inFile = new Scanner(srcFile);
        
        i = 0;
        while (inFile.hasNext() && i < NUM_PLANETS) {
            String line = inFile.nextLine();
	    String[] tokens = line.split("[:]+");
            if (tokens.length != 2) {
	        System.out.println("ERROR: incorrect format of line " + (i+1));
		System.exit(1);
            }
            planetIn[i] = tokens[0];
            moonsIn[i] = Integer.parseInt(tokens[1]);
            i++;
        }
        inFile.close();  // close the file

        //////////////////////////////////////////////////////////
        // print the planet and moon information out to the console
        //////////////////////////////////////////////////////////
        
        for (i = 0; i < NUM_PLANETS; i++) {
            System.out.println(planetIn[i] + " has " + moonsIn[i] + " moons");
        }
    }
}
