In: Computer Science
Class,
Let's 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. Deposit Cash.
B. Withdraw Cash
X. Exit
Enter your Selection:
3. Prompt for the value menuChoice.
4. If menuChoice is "A", display "Do Deposit" and redisplay the menu.
If menuChoice is "B", display "Do withdrawal" 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.
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'.
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.
Step 1 - Create a file BankMenu.java. Its content will be
import java.util.Scanner;
public class BankMenu {
private static void doDeposit() {
System.out.println("Do Deposit");
}
private static void doWithdraw() {
System.out.println("Do withdrawal");
}
public static void main(String[] args) {
char menuChoice;
Scanner sc = new Scanner(System.in);
do {
System.out.println("\n"); // For Output Formatting
System.out.println("A. Deposit Cash.");
System.out.println("B. Withdraw Cash");
System.out.println("X. Exit");
System.out.print("Enter your Selection: ");
menuChoice = sc.next().charAt(0); // Taking input from user
menuChoice = Character.toUpperCase(menuChoice); // Converting input to UpperCase character;
switch(menuChoice){
case 'A': doDeposit();
break;
case 'B': doWithdraw();
break;
case 'X': break;
default: System.out.println("Invalid Choice");
}
} while(menuChoice != 'X');
}
}
Step 2- Compile this file using command javac BankMenu.java
Step 3 - Run this file using command java BankMenu
I am attaching a screenshot with sample input and output
You can clearly see in the picture
- For input, a and A.It is printing Do Deposit
- For input, b and B.It is printing Do withdrawal
- For input, c. It is printing Invalid Choice
- For input X. The program got exited.
Similarly, you can check for multiple inputs. Please let me know if you want further explanations in the comment section.