Solved

Command line menu - Java

Posted on 2007-12-03
10
2,280 Views
Last Modified: 2013-11-23
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
0
Comment
Question by:bustin_beanie
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
  • 3
10 Comments
 
LVL 16

Expert Comment

by:ellandrd
ID: 20397817
0
 

Author Comment

by:bustin_beanie
ID: 20398353
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
 
LVL 16

Expert Comment

by:ellandrd
ID: 20401492
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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:bustin_beanie
ID: 20401564
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
 
LVL 16

Expert Comment

by:ellandrd
ID: 20401598
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
 
LVL 16

Accepted Solution

by:
ellandrd earned 125 total points
ID: 20401722
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
 
LVL 35

Expert Comment

by:TimYates
ID: 20402041
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
 
LVL 35

Expert Comment

by:TimYates
ID: 20848965
:-(  oh well ;-)  I suppose it killed a rainy morning ;-)
0
 

Author Comment

by:bustin_beanie
ID: 20849021
it was very good, but a bit too copmplex for me!
0
 
LVL 35

Expert Comment

by:TimYates
ID: 20849049
Fair enough :-)

Good luck with it :-)
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
This video teaches viewers about errors in exception handling.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

730 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question