2

I made a method in java that prints a menu screen that looks like this:

MENU
c - Number of whitespace characters
f - Find text
r - Replace all !'s
q - Quit

Choose an option:

The method returns a char. How do I use the return value of the method in main to make if else statements?

printMenu method:

public static char printMenu(Scanner scnr) {
      char menuOp;

      //display the menu
      System.out.println("\nMENU");
      System.out.println( "c - Number of whitespace characters");
      System.out.println("f - Find text");
      System.out.println("r - Replace all !\'s");
      System.out.println("q - Quit\n");

      menuOp = ' ';

      //loop until the user has entered a c, f, r or q
      while (menuOp != 'c' && menuOp != 'f' &&
                menuOp != 'r' &&  
                menuOp != 'q') {
         System.out.println( "Choose an option:");
         menuOp = scnr.nextLine().charAt(0);
      }

      //return the letter that the user entered
      return menuOp;
   }  //end of the printMenu method

What I want to be able to do in main:

while (return value from printMenu method != 'q'){

      printMenu(scnr);
      if (return value from printMenu method == 'c'){ //do this                    
      }
      else if (return value from printMenu method == 'f'){ //do this
      }
      else if (return value from printMenu method == 'r'){ //do this
      }
   }
}

I'm still new and really appreciate the help, patience, and kindness. Thanks

Edit - I have to use the return value from printMenu() as a requirement for a project.

2
  • 1
    Hint: look at the line menuOp = scnr.nextLine().charAt(0);. Here you are assigning the return value of charAt to menuOp. You should try doing something similar with printMenu too! Commented Apr 1, 2020 at 8:08
  • Awesome hint, that put me another step in the right direction, thanks sweeper! Commented Apr 1, 2020 at 8:22

2 Answers 2

3

This seems like a good example for using a do-while loop:

    Scanner scanner = new Scanner(System.in);
    char c;
    do
    {
        c = printMenu(scanner);
        switch (c)
        {
            case 'c':
                //do something
                break;
            case 'f':
                //do something
                break;
            case 'r':
                //do something
                break;

        }
    } while(c != 'q');
Sign up to request clarification or add additional context in comments.

Comments

0

Answered by sweeper:

menuChar = printMenu(scnr);

Comments

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.