-2

One of the requirements of my project is that the program loops until the user presses the "X" key. I have the method for this, but the program terminates even when the method is not called. Here is my code:

while (terminate == false)
{
    // Ask user for input

    switch (command)
    {
        case "I":
        {
            // Do stuff
        }

        case "X":
        {
            terminateProgram();
        }
    }
}

This is my terminate method:

private static boolean terminateProgram()
{
    terminate = true;
    return terminate;
}

Even if I enter the "I" key, the loop ends after the case for "I" is completed. "I" works normally if terminateProgram(); is commented. How do I get the loop to stop only when I enter "X"?

user3479783
  • 69
  • 1
  • 2
  • 10
  • For starters...you're not doing anything with the variable after you return from your method call... – Makoto Sep 24 '14 at 04:03

1 Answers1

3

You need a break within each case statement.

Read up on fall-through, which is what your current code is doing.

while (!terminate)
{
    // Ask user for input

    switch (command)
    {
        case "I":
        {
            // Do stuff
            break;
        }

        case "X":
        {
            terminateProgram()
            break;
        }
        default:
            // Do something default if no condition is met.
    }
}

Then here:

private static void terminateProgram()
{
    terminate = true; // if this method simply is to terminate a program
                      // I'm not quite sure why you need a `terminate` variable
                      // unless you're using it in another part of the program.
                      // A simple system.exit(0) would suffice.
    System.exit(0);
}
Community
  • 1
  • 1
theGreenCabbage
  • 5,197
  • 19
  • 79
  • 169
  • 2
    And dont make terminate == false, use !terminate – DiogoSantana Sep 24 '14 at 04:02
  • When you press `X`, `terminateProgram()` sets `terminate` to true. Do you have `terminate` as a global variable? Better question - where do you declare `terminate`? (Consider learning OOP concepts so you don't need to do everything statically ;)) – theGreenCabbage Sep 24 '14 at 04:07
  • There's actually more to your code that can be improved. As far as I can tell, your `terminateProgram()` is simply modifying `terminate`, so you don't need a `return` value. Change `bool` to `void`. Unless you plan to do more with `terminateProgram()`, it's unnecessary. A simple `terminate = true` would suffice in place of the method call. – theGreenCabbage Sep 24 '14 at 04:09
  • Feel free to accept the answer if it helped you =). – theGreenCabbage Sep 24 '14 at 10:15