Command line menu - Java

What is the simplest way to create a java command-line menu?
I need to create a menu with 3-4 submenus, and need to be able to return to the parent menu as the last option of each menu.
example)
main menu
-----------
1. option 1
2. option 2
3. option 3

(select option 2)

option 2 menu
---------------
1. suboption 1
2. suboption 2
3. suboption 3
4. exit (to main menu)

(select suboption 1)

suboption 1 menu
---------------------
1. sub-suboption 1
2. sub-suboption 2
3. exit (return to option 2 menu)

should i make a new class, or create the menu in a test class with do-while loops and switch statements?

thanks
bustin_beanieAsked:
Who is Participating?
 
ellandrdConnect With a Mentor Commented:
Since its Tuesday and I'm free for the next hour here you go...
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
 
public class Main {
 
    BufferedReader br;
    int selectedOption;
 
    public Main() {
        showMainMenu();
        br = new BufferedReader(new InputStreamReader(System.in));
        try {
            selectedOption = Integer.parseInt(br.readLine());
            switch (selectedOption) {
                case 1:
                    showSubMenuOptions(1);
                    break;
                case 2:
                    showSubMenuOptions(2);
                    break;
                case 3:
                    quitProgram();
                    break;
            }
        } catch (IOException ioe) {
            System.out.println("IO error trying to read your input." + ioe);
            System.exit(1);
        }
    }
 
    public void showMainMenu() {
        System.out.println("");
        System.out.println("Main Menu");
        System.out.println("---------------------------");
        System.out.println("1. See submenu 1");
        System.out.println("2. See submenu 2");
        System.out.println("3. Exit the program");
        System.out.println("----------------------------");
        System.out.println("");
        System.out.print("Please select an option from 1-3");
        System.out.println("");
        System.out.println("");
    }
 
    public void showSubMenuOptions(int mainMenuChoice) {
        switch (mainMenuChoice) {
            case 1:
                System.out.println("");
                System.out.println("Sub-Menu 1 Options");
                System.out.println("---------------------------");
                System.out.println("1. Back to main menu");
                System.out.println("");
                break;
            case 2:
                System.out.println("");
                System.out.println("Sub-Menu 2 Options");
                System.out.println("---------------------------");
                System.out.println("1. Back to main menu");
                System.out.println("");
                break;
        }
        
        br = new BufferedReader(new InputStreamReader(System.in));
        try {
            selectedOption = Integer.parseInt(br.readLine());
            switch (selectedOption) {
                case 1:
                    new Main();
                    break; 
            }
        } catch (IOException ioe) {
            System.out.println("IO error trying to read your submenu input." + ioe);
            System.exit(1);
        }
    }
 
    public void quitProgram() {
        System.out.println("You have quit the program");
        System.exit(1);
    }
 
    public static void main(String[] args) {
        new Main();
    }
}

Open in new window

0
 
bustin_beanieAuthor Commented:
hi,

thanks for the response.  i need to however implement the menu throught the command line (system.out.print), without using any graphics environment.  i assume this MenuItem class cannot be used for this, any other suggestions?
thanks
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
ellandrdCommented:
Ah OK - here is a nice working example...

ellandrd
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
 
public class Main {
    public Main() {
    }
    
    public static void main(String[] args) {
        System.out.println("Example Program");
        System.out.println("");
        System.out.println("Menu Options:");
        System.out.println("1. Some menu option");
        System.out.println("2. Some menu option");
        System.out.println("3. Some menu option");
        System.out.println("4. Some menu option");
        System.out.println("5. Exit the program");
        System.out.println("");
        System.out.print("Please select an option from 1-5\r\n");
        
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        try {
            int input = Integer.parseInt(br.readLine());
            
            if(input < 0 || input > 5) {
                System.out.println("You have entered an invalid selection, please try again\r\n");
            } else if(input == 5) {
                System.out.println("You have quit the program\r\n");
                System.exit(1);
            } else {
                System.out.println("You have entered " + input + "\r\n");
            }
        } catch (IOException ioe) {
            System.out.println("IO error trying to read your input!\r\n");
            System.exit(1);
        }
    }
}

Open in new window

0
 
bustin_beanieAuthor Commented:
thanks again for the response.  but i also need to include 3-4 submenus as described initially, is the best way too achieve this simply through do-while loops and switch statements?
0
 
ellandrdCommented:
i would use switch statement to control which submenu displayed next.

after you get the input - check the number.  if 1 shown submenu options for 1.  if 2 shown submenu options belong to 2 etc etc

give it a go yourself.  if you get stuck i will help you more.  you will not learn if i post all the code for you...
0
 
TimYatesCommented:
I got bored as well...  Here's another possibility...
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
 
public class TextMenu
{
  class Menu
  {
    private List<MenuItem> items = new ArrayList<MenuItem>() ;
    private String title ;
 
    public Menu( String title )
    {
      this.title = title ;
    }
 
    public Menu doOption( int option )
    {
      if( option == 0 ) return null ;
      option-- ;
      if( option >= items.size() )
      {
        System.out.println( "Unknown option " + option ) ;
        return this ;
      }
      items.get( option ).select() ;
      Menu next = items.get( option ).getSubMenu() ;
 
      return next == null ? this : next ;
    }
 
    public Menu addItem( MenuItem item )
    {
      items.add( item ) ;
      return this ;
    }
 
    public String toString()
    {
      StringBuilder sb = new StringBuilder() ;
      sb.append( title ).append( "\n" ) ;
      for( int i = 0 ; i < title.length() ; i++ )
      {
        sb.append( "-" ) ;
      }
      sb.append( "\n" ) ;
      for( int i = 0 ; i < items.size() ; i++ )
      {
        sb.append( ( i + 1 ) ).append( ") " ).append( items.get( i ) ).append( "\n" ) ;
      }
      sb.append( "0) Quit" ) ;
      return sb.toString() ;
    }
  }
 
  class MenuItem
  {
    private String title ;
    private Menu submenu ;
    private ActionListener onselect ;
 
    public String getTitle()
    {
      return title;
    }
 
    public MenuItem( String title, Menu submenu, ActionListener onselect )
    {
      this.title = title ;
      this.submenu = submenu ;
      this.onselect = onselect ;
    }
 
    public void setSubMenu( Menu submenu )
    {
      this.submenu = submenu ;
    }
 
    public void select()
    {
      if( onselect != null )
        onselect.actionPerformed( new ActionEvent( this, 0, "select" ) ) ;
    }
 
    public Menu getSubMenu()
    {
      return submenu ;
    }
 
    public String toString()
    {
      return title ;
    }
  }
 
  public Menu createMenuSystem()
  {
    MenuItem backLink = new MenuItem( "Item 2 Goes back to the root menu", null, null ) ; // tie this up in a bit
 
    Menu subMenu2 = new Menu( "Submenu 2" ) ;
    subMenu2.addItem( new MenuItem( "Item 1 prints Tim Yates", null, new ActionListener() {
      public void actionPerformed( ActionEvent e ) {
        System.out.println( "Tim Yates!" ) ;
      }
    } ) ).addItem( backLink ) ;
 
    Menu subMenu1 = new Menu( "Submenu 1" ) ;
    subMenu1.addItem( new MenuItem( "Item 1 prints hello", null, new ActionListener() {
      public void actionPerformed( ActionEvent e ) {
        System.out.println( "hello!" ) ;
      }
    } ) ).addItem( new MenuItem( "Item 2 goes to the next submenu (submenu2)", subMenu2, null ) )
    .addItem( new MenuItem( "Item 3 quits", null, new ActionListener() {
      public void actionPerformed( ActionEvent e ) {
        System.exit( 1 ) ;
      }
    } ) );
 
    Menu rootMenu = new Menu( "ROOT" ) ;
    rootMenu.addItem( new MenuItem( "Go to the 1st submenu (subMenu1)", subMenu1, null ) )
            .addItem( new MenuItem( "Go to the 2nd submenu (subMenu2)", subMenu2, null ) ) ;
 
    // Tie the backlink up
    backLink.setSubMenu( rootMenu ) ;
 
    return rootMenu ;
  }
 
  /** Creates a new instance of TextMenu */
  public TextMenu()
  {
  }
 
  public static void main( String[] args )
  {
    BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) ) ;
    TextMenu t = new TextMenu() ;
    Menu currentMenu = t.createMenuSystem() ;
    while( currentMenu != null )
    {
      System.out.println( currentMenu ) ;
      System.out.print( "Your Selection : " ) ;
      String inp = "" ;
      try
      {
        inp = br.readLine() ;
        currentMenu = currentMenu.doOption( Integer.parseInt( inp ) ) ;
      }
      catch( Exception ex )
      {
        System.out.println( "Didn't understand " + inp ) ;
      }
    }
  }
}

Open in new window

0
 
TimYatesCommented:
:-(  oh well ;-)  I suppose it killed a rainy morning ;-)
0
 
bustin_beanieAuthor Commented:
it was very good, but a bit too copmplex for me!
0
 
TimYatesCommented:
Fair enough :-)

Good luck with it :-)
0
All Courses

From novice to tech pro — start learning today.