0

sorry for asking such an in depth question, but I'm very lost. I am working on a problem and I am stuck. I am supposed to make a basic menu driven calculator that add, subtract, multiply, divide, or generate a random number between an upper and lower limit. I made that without too much difficulty, but now I need to change it so that after it performs an operation it starts over again and displays the menu. Also, if I enter an invalid response, it needs to let them try again until they enter a valid one UNLESS they enter an invalid response THREE TIMES IN A ROW; then it needs to display a message about trying again later and exiting the program. This is there I am stuck. I have tried every combination of for and while in the following code but i can not get this to work. I would really appreciate any pointers.

Here are the requirements:

  • The menu is repeatedly displayed until a valid option is entered
  • If the user enters three invalid choices in a row, the program ends
  • If the user enters two invalid choices, then a valid one, then another invalid one, the program does NOT end
  • The program computes the correct answers for each menu option
  • The program continues after a valid operation by re-displaying the menu
  • The program ends when the user chooses the Quit option from the menu • The program does not end on division by zero – just display an error message and allow the user to retry

And here is what i have thus far.

import java.util.Scanner;

public class BasicCalculator {

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    double numONE = 0.0;
    double numTWO = 0.0;
    double upperLimit = 0.0;
    double lowerLimit = 0.0;

    System.out.println("MENU");
    System.out.println("1. +");
    System.out.println("2. -");
    System.out.println("3. *");
    System.out.println("4. /");
    System.out.println("5. Generate a random number.");
    System.out.println("6. Quit");

    System.out.println("What would you like to do?");
    int menuSelect = input.nextInt();
    //Selects an item from the menu

    if(menuSelect == 1 || menuSelect == 2 || menuSelect == 3 || menuSelect == 4){
        System.out.println("Enter first number.");
        numONE = input.nextDouble();
        //Stores input as numONE

        System.out.println("Enter second number.");
        numTWO = input.nextDouble();
        //Stores input as numTWO
    }
    if(menuSelect == 1){
        System.out.println(numONE + numTWO);
        //Adds two numbers
    }
    else if(menuSelect == 2){
        System.out.println(numONE - numTWO);
        //Subtracts second number from first number
    }
    else if(menuSelect == 3){
        System.out.println(numONE * numTWO);
        //Multiplies two numbers
    }
    else if(menuSelect == 4){
        if(numTWO != 0){
            System.out.println(numONE / numTWO);
            //Divides first number by second number
        }
        else if(numTWO == 0){
            System.out.println("I'm sorry, you cannot divide by zero.");
        }
    }
    else if(menuSelect == 5){
        System.out.println("Enter upper limit.");
        upperLimit = input.nextDouble();
        System.out.println("Enter lower limit.");
        lowerLimit = input.nextDouble();
        double randomVal = (lowerLimit + (int)(Math.random() * ((upperLimit - lowerLimit)+1)));
        System.out.println(randomVal);
        //Displays a random integer between an upper and a lower limit
    }
    else if(menuSelect==6){
        System.out.println("Goodbye");
        System.exit(0);
    }
    else{
        System.out.println("Sorry, "+menuSelect+" is not an option.");
    }
}
}
1
  • Btw: bullet points in markdown are made by starting each item with a dash (-). There's a tool button in the editor to help out, too. Commented Jan 24, 2014 at 14:20

5 Answers 5

2

Look at lines I added ( // <- new code )

import java.util.Scanner;

public class BasicCalculator {

public static void main(String[] args) {

    int counter_WrongAttempts = 0;    // <- new code
    boolean flag_Quit = false;        // <- new code
    while (!flag_Quit) {              // <- new code
        boolean wrongAttempt = false; // <- new code


        Scanner input = new Scanner(System.in);

        double numONE = 0.0;
        double numTWO = 0.0;
        double upperLimit = 0.0;
        double lowerLimit = 0.0;

        System.out.println("MENU");
        System.out.println("1. +");
        System.out.println("2. -");
        System.out.println("3. *");
        System.out.println("4. /");
        System.out.println("5. Generate a random number.");
        System.out.println("6. Quit");

        System.out.println("What would you like to do?");
        int menuSelect = input.nextInt();
        //Selects an item from the menu

        if(menuSelect == 1 || menuSelect == 2 || menuSelect == 3 || menuSelect == 4){
            System.out.println("Enter first number.");
            numONE = input.nextDouble();
            //Stores input as numONE

            System.out.println("Enter second number.");
            numTWO = input.nextDouble();
            //Stores input as numTWO
        }
        if(menuSelect == 1){
            System.out.println(numONE + numTWO);
            //Adds two numbers
        }
        else if(menuSelect == 2){
            System.out.println(numONE - numTWO);
            //Subtracts second number from first number
        }
        else if(menuSelect == 3){
            System.out.println(numONE * numTWO);
            //Multiplies two numbers
        }
        else if(menuSelect == 4){
            if(numTWO != 0){
                System.out.println(numONE / numTWO);
                //Divides first number by second number
            }
            else if(numTWO == 0){
                System.out.println("I'm sorry, you cannot divide by zero.");
            }
        }
        else if(menuSelect == 5){
            System.out.println("Enter upper limit.");
            upperLimit = input.nextDouble();
            System.out.println("Enter lower limit.");
            lowerLimit = input.nextDouble();
            double randomVal = (lowerLimit + (int)(Math.random() * ((upperLimit - lowerLimit)+1)));
            System.out.println(randomVal);
            //Displays a random integer between an upper and a lower limit
        }
        else if(menuSelect==6){
            System.out.println("Goodbye");
            System.exit(0);
            flag_Quit = true;                                  // <- new code
        }
        else{
            System.out.println("Sorry, "+menuSelect+" is not an option.");
            wrongAttempt = true;                               // <- new code
        }


        if (wrongAttempt)                                      // <- new code
            counter_WrongAttempts++;                           // <- new code
        else                                                   // <- new code
            counter_WrongAttempts = 0;                         // <- new code
        flag_Quit = flag_Quit || (counter_WrongAttempts >= 3); // <- new code

    }
}
}
Sign up to request clarification or add additional context in comments.

1 Comment

I'd remove the System.exit(0) then. But I agree this is an cleaner way to quit the program (by letting it finish instead of terminating).
2

This isn't about a 'for loop inside a while loop', you don't even need it.

Imagine the following pseudo-code:

int invalidOptions = 0;
while ( invalidOptions < 3 ) {

    // show menu
    displayMenu();

    // read option
    int input = readInput();

    // validate input
    if ( isInputValid(input) ) {
        // check whether the user wants to exit or not
        if (input == EXIT_INPUT) {
            break;
        }

        // handle other commands
        handleInput(input);
    } else {
        // input is invalid
        invalidOptions++;
    }
}

That's all you need, it's better to split your program into smaller pieces, it will be easier to maintain and understand.

Comments

1

First things first, you don't really need four variables for this program. Since you are always taking two numbers as input you can easily store them in two variables, instead of having different variable names for each case. As mentioned above, you don't need such complex loop nesting. A simple while that checks the number of errors is less than 3 will do just fine. Also, you seem to work well with the System.out.println() command, but for some applications, like input, it may be better to work with System.out.print(), it's basically the same but does not start a new line. Try the code below to see the results. Another thing you might consider is using a switch sentence instead of the if, else if, else if statements.

import java.util.Scanner;

public class BasicCalculator {

  public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    double firstNumber = 0.0;
    double secondNumber = 0.0;

    //New variable
    int errors = 0;

    while (errors < 3) {
        System.out.println("MENU");
        System.out.println("1. +");
        System.out.println("2. -");
        System.out.println("3. *");
        System.out.println("4. /");
        System.out.println("5. Generate a random number.");
        System.out.println("6. Quit");

        System.out.println("What would you like to do?");
        System.out.print("> ");
        int menuSelect = input.nextInt();
        //Selects an item from the menu

        if(menuSelect == 1 || menuSelect == 2 || menuSelect == 3 || menuSelect == 4) {
            errors = 0;
            System.out.print("Enter first number: ");
            firstNumber = input.nextDouble();
            //Stores input as the firstNumber

            System.out.print("Enter second number: ");
            secondNumber = input.nextDouble();
            //Stores input as the secondNumber
        }
        if(menuSelect == 1){
            System.out.println(firstNumber + secondNumber);
            //Adds two numbers
        }
        else if(menuSelect == 2){
            System.out.println(firstNumber - secondNumber);
            //Subtracts second number from first number
        }
        else if(menuSelect == 3){
            System.out.println(firstNumber * secondNumber);
            //Multiplies two numbers
        }
        else if(menuSelect == 4){
            if(secondNumber != 0){
                System.out.println(firstNumber / secondNumber);
                //Divides first number by second number
            }
            else if(secondNumber == 0){
                System.out.println("I'm sorry, you cannot divide by zero.");
            }
        }
        else if(menuSelect == 5){
            errors = 0;
            System.out.print("Enter upper limit: ");
            firstNumber = input.nextDouble();
            System.out.print("Enter lower limit: ");
            secondNumber = input.nextDouble();
            double randomVal = (firstNumber + (int)(Math.random() * ((firstNumber - secondNumber)+1)));
            System.out.println(randomVal);
            //Displays a random integer between an upper and a lower limit
        }
        else if (menuSelect==6){
            System.out.println("Goodbye");
            System.exit(0);
        }
        else{
            errors++;
            System.out.println("Sorry, "+ menuSelect + " is not an option.");
        }
    }       
    input.close();
    System.out.println("Program will exit now");
  }
}

Comments

0
int unvalid = 0;
while (unvalid < 3)
{
  //read stuff
  if ([stuff is valid])
  {
    unvalid = 0;
  }
  else
  {
    unvalid++;
  }
}

Comments

0

You probably don't want a for loop inside a while loop to handle this. I would just have a variable to track how many invalid inputs you've received, increment it when they enter something invalid, reset it to zero if they enter something valid, and kick them out if it gets too high.

eg:

import java.util.Scanner;

public class BasicCalculator {

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    double numONE = 0.0;
    double numTWO = 0.0;
    double upperLimit = 0.0;
    double lowerLimit = 0.0;
    int invalid = 0;

    System.out.println("MENU");
    System.out.println("1. +");
    System.out.println("2. -");
    System.out.println("3. *");
    System.out.println("4. /");
    System.out.println("5. Generate a random number.");
    System.out.println("6. Quit");

    System.out.println("What would you like to do?");
    int menuSelect = input.nextInt();
    //Selects an item from the menu

    while(invalid < 3){
    if(menuSelect == 1 || menuSelect == 2 || menuSelect == 3 || menuSelect == 4){
        System.out.println("Enter first number.");
        numONE = input.nextDouble();
        //Stores input as numONE

        System.out.println("Enter second number.");
        numTWO = input.nextDouble();
        //Stores input as numTWO
        invalid = 0;
    }
    if(menuSelect == 1){
        System.out.println(numONE + numTWO);
        //Adds two numbers
    }
    else if(menuSelect == 2){
        System.out.println(numONE - numTWO);
        //Subtracts second number from first number
    }
    else if(menuSelect == 3){
        System.out.println(numONE * numTWO);
        //Multiplies two numbers
    }
    else if(menuSelect == 4){
        if(numTWO != 0){
            System.out.println(numONE / numTWO);
            //Divides first number by second number
        }
        else if(numTWO == 0){
            System.out.println("I'm sorry, you cannot divide by zero.");
        }
    }
    else if(menuSelect == 5){
        System.out.println("Enter upper limit.");
        upperLimit = input.nextDouble();
        System.out.println("Enter lower limit.");
        lowerLimit = input.nextDouble();
        double randomVal = (lowerLimit + (int)(Math.random() * ((upperLimit - lowerLimit)+1)));
        System.out.println(randomVal);
        //Displays a random integer between an upper and a lower limit
        invalid = 0;
    }
    else if(menuSelect==6){
        System.out.println("Goodbye");
        System.exit(0);
    }
    else{
        System.out.println("Sorry, "+menuSelect+" is not an option.");
        invalid++;
    }
    }
    System.out.println("Too many invalid inputs. Try again later");
}
}

2 Comments

This worked wonderfully. I added invalid=0; to the end of if statements 1 thru 5 because the invalid inputs need to be consecutive to discontinue the program, and i moved while(invalid<3) to above the menu, because the menu needs to reprint after each entered response and it couldn't be better. Thanks everyone.
Yeah, I noticed a few minutes ago that I was missing the invalid reset for case 5. Wasn't sure if you wanted the menu reprinting or not

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.