In: Computer Science
Create a menu in Java. A menu is a presentation of options for you to select.
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.
5 point bonus - 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.
5 point bonus - 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.
Program code:
import java.util.Scanner; //Importing Scanner class
public class menuChoice
{
public static void main(String [] args)
{
String
menuChoice;
//Creating string variable to store user's
choice
boolean
i=true;
//Creating boolean variable for loop
iteration
Scanner read=new
Scanner(System.in);
//Creating scanner variable to read user's
choice
while(i)
//loop for displaying menu until user want to
exit.
{
System.out.println("\nMenu...");
//Displaying menu
System.out.println("A.Buy Stock");
System.out.println("B.Sell Stock");
System.out.println("X.Exit");
System.out.print("\nEnter your choice :
");
menuChoice=read.next();
//Reading user value
if(menuChoice.equals("a")||
menuChoice.equals("A"))
//Checking whether he entered 'A' or 'a'
{
menuChoice=menuChoice.toUpperCase();
//Converting input into upper case.
choiceA();
//Calling method to display option A value
}
else if(menuChoice.equals("b")||
menuChoice.equals("B"))
{
menuChoice=menuChoice.toUpperCase();
//Converting input into upper case.
choiceB();
//Calling method to display option B value
}
else if(menuChoice.equals("x")||
menuChoice.equals("X"))
{
i=false;
//Making i=false to exit from the loop
menuChoice=menuChoice.toUpperCase();
//Converting input into upper case.
}
else
System.out.println("Invalid
selection.....Please select one from the above.");
}
}
static void
choiceA()
//Method to print BUY STOCK
{
System.out.println("BUY STOCK");
}
static void
choiceB()
//Method to print SELL STOCK
{
System.out.println("SELL STOCK");
}
}
Output: