Interactive Menu Selection
Stryg for at vise menuen
Interactive programs often need to present users with a set of options and respond based on their selection. This is commonly done using a menu-driven approach, where you display a menu, prompt the user to pick an option, and then perform an action based on their choice. In Java, you can use the Scanner class to capture the user's input for menu selection. The typical flow involves displaying the menu, reading the user's selection as an integer or string, and then branching your program logic depending on what the user chose.
Main.java
1234567891011121314151617181920212223242526272829package com.example; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("=== Main Menu ==="); System.out.println("1. Say Hello"); System.out.println("2. Show Current Time"); System.out.println("3. Exit"); System.out.print("Enter your choice (1-3): "); int choice = scanner.nextInt(); if (choice == 1) { System.out.println("Hello, user!"); } else if (choice == 2) { System.out.println("The current time is: " + java.time.LocalTime.now()); } else if (choice == 3) { System.out.println("Goodbye!"); } else { System.out.println("Invalid choice. Please run the program again."); } scanner.close(); } }
When handling user choices in menu-driven programs, it is common to use a switch statement to select the action based on the user's input. The switch statement allows your code to be more organized and readable, especially when you have several menu options. Instead of writing multiple if-else statements, you can use switch with the user's input value to jump directly to the code that should run for each menu item.
Tak for dine kommentarer!
Spørg AI
Spørg AI
Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat