Solution: Build a Quiz

  • import java.util.Scanner; – imports the Scanner class to read user input.

  • public class Main – defines the class Main.

  • public static void main(String[] args) – main method where the program starts.

  • Scanner input = new Scanner(System.in); – creates a Scanner object for keyboard input.

  • Print statements – display a multiple-choice question about the capital of France.

  • int answer = input.nextInt(); – reads the user’s numeric choice (1–3).

  • switch (answer) – checks which option the user selected:

    • case 1: prints that Berlin is the capital of Germany.

    • case 2: prints that Madrid is the capital of Spain.

    • case 3: prints that Paris is the correct answer.

    • default: prints "Invalid choice." for any other number.

  • input.close(); – closes the Scanner to free system resources.

Solution: Build a Quiz

  • import java.util.Scanner; – imports the Scanner class to read user input.

  • public class Main – defines the class Main.

  • public static void main(String[] args) – main method where the program starts.

  • Scanner input = new Scanner(System.in); – creates a Scanner object for keyboard input.

  • Print statements – display a multiple-choice question about the capital of France.

  • int answer = input.nextInt(); – reads the user’s numeric choice (1–3).

  • switch (answer) – checks which option the user selected:

    • case 1: prints that Berlin is the capital of Germany.

    • case 2: prints that Madrid is the capital of Spain.

    • case 3: prints that Paris is the correct answer.

    • default: prints "Invalid choice." for any other number.

  • input.close(); – closes the Scanner to free system resources.