Overclock.net › How To's › Java - How To Loop A Program To Keep Running

Java - How To Loop A Program To Keep Running

Simple Java Programming How-To to keep a Program running unless the user wants it to end.
OCN JAVA Code Example - 001 - Looping a Program To Keep Running
Version 1.01

Written By:
RC (thanks rush2049 for ideas and fixes!)

This is a simple program / menu for accessing the different features and to continue
running until its told not to. 

Beginner to Intermediate


In programming there is no one correct way to do these things, but there maybe times that it is better to do it one way or another. Here is a general example of how one might loop a console based program in a recent project I had due.

As Java is OOP, I will break up the code into code blocks by methods. I have taken parts out that really didn't matter to this particular example so if I make a mistake feel free to ask or point it out.

Some of the code is broken down due to thought process that many people would potentially be working on it. I prefer working alone, but this particular class is forcing me to play nicely with others. This code is not "business" code, its not built for efficiency but for efficacy. It needs to work - so the target audience is primarily low level programming courses.

I have never shared anything I have ever worked on so any advice, comments, suggestions are more than welcome. Just don't hurt my feelings thumb.gif

Concepts: Importing Packages
//This goes above your class declaration, this is importing the Scanner class.
import java.util.Scanner;

Concepts: Storing Console Arguments, Modular Coding, Conditionals.
//The following code blocks go into your home made class!
public static void main(String[] args)
        String fileName = new String("");
        //If console argument exists it is the default file name until
        if (args.length != 0)
                fileName = args[0];
                fileName = "NONE!";
        //Starts the program's user interfaces.  This code is executed by calling this method
        //This is good example of modularity.

// The original point of this program was to make a Database, this is a made class/object and not one built directly into the Java libraries.

Concepts: Boolean Datatype, Java Switch Statement Using Block Code, Input Parameters, While Loop
public static void runProgram(String fileName)
        //Program keeps running till this condition updates. Only updates
        //if the user "chooses" quit option.
        Boolean keepRunning = true;
        //User choice from the menu is stored here.
        Integer userChoice = 0;
        //This is the master controller of our file.  Program is looped
        //to run infinitely until user decides to terminate.
                //This assignment stores the return value of the showMenu
                //to the integer userChoice.  This method is defined
                //in the following block of code.
                userChoice = showMenu(fileName);
                //This switch statement handles all the individual choices one may
                //have in the main menu.
                        //Option 1: Set The FileName
                        case 1:
                                //Break tells the switch when to stop executing once its reached this case.

                        //Example Case without the Block statement braces.  This
                        //is perfectly acceptable.
                        //Option 2: Make A Database and Default Sort It.
                        case 2;         
                        //Option 3: Print the Database Out.
                        case 3:
                        //Option 4: Execute the Search Database Method.
                        case 4:
                        //Option 5: Display the authors to the users.
                        case 5:
                        //Option 6: Exits the run loop and thereby the entire program.
                        case 6:
                                keepRunning = false;
                        //Handles conditions that were unexpected.

Concepts Used: Integer Parsing (String to Integer), Try And Catch, Scanner, Printing to Screen (PrintLN), Auto toString Utilization (fileName in a println method), Conditional Logic / Boolean Algebra and && Syntax)
public static int showMenu(String fileName) throws NumberFormatException
        //You can also use the primitive type int instead of Integer
        //The memory footprint is much smaller using just a primitive
        //as opposed an Object of Integer.
        //int intChoice = 0;
        Integer intChoice = 0;

        String strChoice = new String("");

        //Extremely useful Object/Class provided by Sun/Oracle (read more about it!)
        Scanner userInput = new Scanner(System.in);
        System.out.println("|    Welcome to AllYourDATABASE!    |");
        System.out.println("|                                   |");
        System.out.println("| Main Menu:                        |");
        System.out.println("| ----------                        |");
        System.out.println("|                                   |");
        System.out.println("| 1.) Choose a filename!            |");
        System.out.println("| 2.) Make a Database!              |");
        System.out.println("| 3.) Display Entire Database!      |");
        System.out.println("| 4.) Search The Database!          |");
        System.out.println("| 5.) About This Program!           |");
        System.out.println("| 6.) Exit!                         |");
        System.out.println("|                             v 1.0 |");
        System.out.println("\n\nCurrent File Name: " + fileName + "\n");
        //This forces it to ask a user and KEEP asking until it gets at least
        //a value from the user of 1 through 6.  Each corresponds to the menu
        //option displayed and the Case statements in the Switch in the above block
        //of code "runProgram".
        while((intChoice <= 1)&&(intChoice >= 6))
                System.out.print("Please choose a valid option: ");
                //The following few lines of code include the "try"
                //and the "catch" blocks could be removed by utilizing
                //the Scanner.nextInt(); instead of next();.  It
                //is usually a good idea not to program unless you
                //absolutely have to, or if you want to specifically
                //handle the errors yourself (i.e. prompt user with
                //windows or messages.  Check out Javadocs page
                //about Scanner to learn more about the Scanner
                //class and other methods it has such as hasNext();
                strChoice = userInput.next();
                //Read this as you are telling the compiler to TRY AND DO THE FOLLOWING CODE
                //and if it causes/throws an EXCEPTION, then CATCH IT!  Final was not necessary
                //here but it can be useful to continue some lines of code that are neutral
                //to the condition of the TRY succeeding or failing.
                        intChoice = Integer.parseInt(strChoice);
                catch (NumberFormatException e)
                        //Negative one is often used to represent to the developers/debuggers
                        //an error has occured.  Zero is more often used to represent success.
                        intChoice = -1;
                        System.out.println("Final can execute code regardless!");
        //Returns the choice the user made!
        return intChoice;

Thanks rush2049 for his critiquing tongue.gif

Forum Link: http://www.overclock.net/t/1216424/java-example-code-looping-a-program-to-keep-running/0_50#post_16483525

Comments (3)

Very nice, but I use LWJGL and jMonkeyEngine so I'm set.
Thanks for stopping by! I will have to give those a check.

This was more like a simple lesson / quick start for potential college projects.
Those are for games. This isn't a game, and nor does it seem to be aimed at people with enough experience to use those. It seems like something a beginner could learn from, which is what I'd expect.
Overclock.net › How To's › Java - How To Loop A Program To Keep Running