Search code examples
javastringjava.util.scanneruppercaselowercase

string.toUpperCase() and string.toLowercase() not printing


(preface) I actually believe this to be a simple question but im fairly new to programming so it is a bit frustrating for me. This questions pertains to a problem with how uppercase and lowercase string may override each other when displaying executed code.

Code below:

import java.util.Scanner; //need for the scanner class

public class Manip
{   
    public static void main(String[] args)
    {
        String city; //to hold the user input   

        //create the scanner object here
        Scanner keyboard = new Scanner(System.in);

        //get the favorite city
        //prompt the user to input the favorite city
        System.out.print("Enter favorite city: ");      

        //read and store into city
        city = keyboard.nextLine();

        //display the number of characters.
        System.out.print("String Length :" );
        System.out.println(city.length());

        //display the city in all upper case
        System.out.println(city.toUpperCase() );

        //Display the city in all lower case
        System.out.println(city.toLowerCase() );

        //Display the first character

        keyboard.next();
    }
}

the output of the code is-

enter favorite city: dallas
String Length :6
dallas

the desired output is-

enter favorite city: dallas
String Length :6
DALLAS
dallas

I'm wondering why it is not printing "dallas" twice, as uppercase AND lowercase letters. it seems to be overwriting the input


Solution

  • I ran your code just as it is, and it printed it both in uppercase and lowercase, but I noticed you had a comment that said //Display the first character, and following it, keyboard.next(). This was the only incorrect part. To print the first letter of a string(in this case the string is city), use this line: System.out.println(city.substring(0,1).toUpperCase()); below is an example of the output:

    Enter favorite city: dallas.          
    String Length :6
    DALLAS
    dallas
    D