Solved

Command line menu - Java

Posted on 2007-12-03
10
2,158 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
  • 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
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

 

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

Problems using Powershell and Active Directory?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
allswap challenge 6 99
ForLoop Example 3 49
Android development question 2 37
mysql jsp example issue 32 38
For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

810 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