Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära Interactive Menu Selection | Building Interactive Programs
Java User Input Essentials

bookInteractive Menu Selection

Svep för att visa menyn

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

Main.java

copy
1234567891011121314151617181920212223242526272829
package 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.

question mark

Which control structure is commonly used to handle menu choices in Java?

Vänligen välj det korrekta svaret

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 3. Kapitel 2

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

Avsnitt 3. Kapitel 2
some-alt