我使用Java从用户获得一个字符串输入。我试着让输入的第一个字母大写。

我试了一下:

String name;

BufferedReader br = new InputStreamReader(System.in);

String s1 = name.charAt(0).toUppercase());

System.out.println(s1 + name.substring(1));

这导致了以下编译错误:

类型不匹配:不能从InputStreamReader转换为BufferedReader 不能在基本类型char上调用toUppercase()


当前回答

使用替换方法。

String newWord = word.replace(String.valueOf(word.charAt(0)), String.valueOf(word.charAt(0)).toUpperCase());

其他回答

Java:

简单的一个帮助方法,用于大写每个字符串。

public static String capitalize(String str)
{
    if(str == null || str.length()<=1) return str;
    return str.substring(0, 1).toUpperCase() + str.substring(1);
}

然后调用str = capitalize(str)


科特林:

str.capitalize()

这只是为了告诉你,你没有错。

BufferedReader br = new InputstreamReader(System.in);
// Assuming name is not blank
String name = br.readLine(); 

//No more error telling that you cant convert char to string
String s1 = (""+name.charAt(0)).toUppercase());
// Or, as Carlos prefers. See the comments to this post.
String s1 = Character.toString(name.charAt(0)).toUppercase());

System.out.println(s1+name.substring(1));

注意:这根本不是最好的方法。这只是为了告诉OP,它也可以使用charAt()来完成。;)

String str1 = "hello";
str1.substring(0, 1).toUpperCase()+str1.substring(1);

来自Ameen Mahheen的答案很好,但如果我们有一些双空格字符串,如“hello world”,那么sb.append得到IndexOutOfBounds异常。正确的做法是在这行之前测试,做:

private String capitalizer(String word){
        String[] words = word.split(" ");
        StringBuilder sb = new StringBuilder();
        if (words[0].length() > 0) {
            sb.append(Character.toUpperCase(words[0].charAt(0)) + words[0].subSequence(1, words[0].length()).toString().toLowerCase());
            for (int i = 1; i < words.length; i++) {
                sb.append(" ");
                if (words[i].length() > 0) sb.append(Character.toUpperCase(words[i].charAt(0)) + words[i].subSequence(1, words[i].length()).toString().toLowerCase());
            }
        }
        return  sb.toString();
    }

使用替换方法。

String newWord = word.replace(String.valueOf(word.charAt(0)), String.valueOf(word.charAt(0)).toUpperCase());