In: Computer Science
create a menu in Java. A menu is a presentation of options for you to select. The article above that is in our discussion board may be helpful.
You can do this in the main() method.
1. Create a String variable named menuChoice.
2. Display 3 options for your program. I recommend using 3 System.out.println statements and a 4th System.out.print to show "Enter your Selection:". This needs to be inside the do -- while loop.
A. Buy Stock. B. Sell Stock X. Exit Enter your Selection:
3. Prompt for the value menuChoice.
4. If menuChoice is "A", display "Buy Stock" and redisplay the menu.
If menuChoice is "B", display "Sell Stock" and redisplay the menu.
If menuChoice is "X", the loop needs to terminate.
If any other choice is given, display "Invalid selection" and redisplay the menu.
For grading, I will test with uppercase characters. Review section 5.1 for String comparisons.
Convert the menuChoice to an upper case String after input or as part of the input but before any processing is done. This will allow me to enter 'a' but process as 'A'. You can Google for "Java string uppercase" to see how this is done.
For Task 4 - Create 2 void methods - 1 for option A to call, and another for option B to call. Do the display work only inside these methods and call these methods for these options.
Following line of code is implementation of the above problem.
Two color are used here:
Black is for the actual code and
Strong Cyan is for comments.
import
java.util.Scanner;
// importing scanner
class
public class MenuChoice {
void
display_A() //method for displaying choice A
{
System.out.println("\nBuy
Stock\n");
// "\n" is used for
newline
}
void
display_B()
//method for displaying choice
B
{
System.out.println("\nSell
Stock\n");
// "\n" is used for
newline
}
public static void main(String[] args) {
Scanner input = new
Scanner(System.in);
// Scanner class for input
taking
String menuChoice;
MenuChoice disp = new
MenuChoice();
// creating object of MenuChoice
class
do
{
System.out.println("A. Buy
Stock");
System.out.println("B. Sell
Stock");
System.out.println("X.
Exit");
System.out.println("\nEnter
your Selection:"); //
"\n" is used for newline
menuChoice = input.nextLine();
// taking input from
keyboard
menuChoice =
menuChoice.toUpperCase();
// to make UPPERCASE if it is in
lowercase
switch(menuChoice)
// switch-case started from
here
{
case
"A":
disp.display_A();
// calling option A
break;
case
"B":
disp.display_B();
// calling option B
break;
case
"X":
System.out.println("Exiting... Thank You!\n");
System.exit(0); // for
program termination
break;
default:
System.out.println("\nInvalid Selection\n");
break;
}
}while(true);
}
}