import java.io.*;

public class menus
{
    static BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
    
    public static void main(String[] args)
    {
	while(true)
	    {
		System.out.println("1) Another menu");
		System.out.println("2) A one-off menu");
		System.out.println("3) Silly option");
		System.out.println("4) Quit");

		int i = getMenuOption(4);

		if(i==1)
		    menu2();

		if(i==2)
		    menu3();

		if(i==3)
		    System.out.println("This option does nothing");

		if(i==4)
		    System.exit(0);
	    }
    }

    //continues to perform function until user quits
    private static void menu2()
    {
	boolean thing = true;

	while(thing == true)
	    {
		System.out.println("1) Count to 10");
		System.out.println("2) Previous menu");

		int i = getMenuOption(2);

		if(i==1)
		    countToTen();

		if(i==2)
		    thing = false;
	    }
    }

    private static void countToTen()
    {
	for(int i=1; i<11; i++)
	    {
		System.out.println(i);
	    }
    }

    //performs one function, then drops back to previous menu
    private static void menu3()
    {
	System.out.println("1) Monkey");
	System.out.println("2) Parrot");
	System.out.println("3) Previous menu");

	int i = getMenuOption(3);

	if(i==1)
	    System.out.println("ook");

	if(i==2)
	    System.out.println("screech");

	//if i is 3, the routine will do nothing and drop back
    }

    private static int getMenuOption(int numoptions)
    {       
	boolean notyet = true;
	while(notyet)
	    {
		System.out.print("?");
		String s = new String("");
		
		try
		    {
			s = input.readLine();
		    }
		catch(IOException e)
		    {
			System.out.println(e);
		    }
		
		int i;

		try
		    {
			i = Integer.parseInt(s);
			
			if(i<=numoptions && i>0)
			    {
				return i;
			    }
			else
			    {
				System.out.println("Not an option");
			    }
		    }
		catch(NumberFormatException e)
		    {
			System.out.println("Not an option");
		    }
		
		
	    }
	//never here;
	return -128;
	
    }

}
