我使用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()


当前回答

字符字符不能存储在字符串中。 char和String不能连接。 String. valueof()用于将char转换为String

输入

india

Code

String name = "india";
char s1 = name.charAt(0).toUppercase()); // output: 'I'
System.out.println(String.valueOf(s1) + name.substring(1)); // output: "I"+ "ndia";

输出

India

其他回答

再举一个例子,如何让用户输入的第一个字母大写:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String string = br.readLine();
// handle supplementary characters
IntStream.concat(
        IntStream.of(string.codePointAt(0))
                .map(Character::toUpperCase), string.codePoints().skip(1)
)
.forEach(cp -> System.out.print(Character.toChars(cp)));
String str = "java";
String cap = str.substring(0, 1).toUpperCase() + str.substring(1);
// cap = "Java"

用你的例子:

public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    // Actually use the Reader
    String name = br.readLine();
    // Don't mistake String object with a Character object
    String s1 = name.substring(0, 1).toUpperCase();
    String nameCapitalized = s1 + name.substring(1);
    System.out.println(nameCapitalized);
}
class CapitalizeWords
{
    public static void main(String[] args) 
    {
        String input ="welcome to kashmiri geeks...";

        System.out.println(input);

        String[] str = input.split(" ");

        for(int i=0; i< str.length; i++)
        {
            str[i] = (str[i]).substring(0,1).toUpperCase() + (str[i]).substring(1);
        }

        for(int i=0;i<str.length;i++)
        {
            System.out.print(str[i]+" ");
        }


    }
}

谢谢,我已经阅读了一些评论,并带来了以下内容

public static void main(String args[]) 
{
String myName = "nasser";
String newName = myName.toUpperCase().charAt(0) +  myName.substring(1);
System.out.println(newName );
}

我希望它能有所帮助 祝你好运

public static String capitalizer(final String texto) {

    // split words
    String[] palavras = texto.split(" ");
    StringBuilder sb = new StringBuilder();

    // list of word exceptions
    List<String> excessoes = new ArrayList<String>(Arrays.asList("de", "da", "das", "do", "dos", "na", "nas", "no", "nos", "a", "e", "o", "em", "com"));

    for (String palavra : palavras) {

        if (excessoes.contains(palavra.toLowerCase()))
            sb.append(palavra.toLowerCase()).append(" ");
        else
            sb.append(Character.toUpperCase(palavra.charAt(0))).append(palavra.substring(1).toLowerCase()).append(" ");
    }
    return sb.toString().trim();
}