String manipulator

The problem

Write a program that asks the user to enter the name of his or her favorite city. Use a String variable to store the input. The program should display the following:

  • The number of characters in the city name
  • The name of the city in all uppercase letters
  • The name of the city in all lowercase letters
  • The first character in the name of the city

Breaking it down

public static void main(String[] args) {

    // Create a Scanner object for keyboard input.
    Scanner keyboard = new Scanner(System.in);

    // Get the user's favorite city.
    System.out.print("Enter the name of your favorite city: ");

    String city = keyboard.nextLine();

    // close stream
    keyboard.close();

    // Display the number of characters.
    System.out.println("Number of characters: " + city.length());

    // Display the city name in uppercase characters.
    System.out.println(city.toUpperCase());

    // Display the city name in lowercase characters.
    System.out.println(city.toLowerCase());

    // Display the first character in the city name.
    System.out.println(city.charAt(0));
}

Output

Enter the name of your favorite city: Madison
Number of characters: 7
MADISON
madison
M

Level Up

  • Validate user input to ensure that a city has been entered.