string.toUpperCase() 和 string.toLowercase() 不打印

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

(序言) 我实际上认为这是一个简单的问题,但我相当 编程新手,所以这对我来说有点令人沮丧。这个问题涉及 显示执行代码时大写和小写字符串如何相互覆盖的问题。

代码如下:

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();
    }
}

代码的输出是-

enter favorite city: dallas
String Length :6
dallas

期望的输出是-

enter favorite city: dallas
String Length :6
DALLAS
dallas

我想知道为什么它不打印 "dallas" 两次,作为大写字母和小写字母。它似乎正在覆盖输入

我 运行 你的代码原样,它以大写和小写形式打印,但我注意到你有一条评论说 //Display the first character,然后是 keyboard.next().这是唯一不正确的部分。要打印字符串的第一个字母(在本例中字符串为 city),请使用此行:System.out.println(city.substring(0,1).toUpperCase()); 下面是输出示例:

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