我使用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()
以下是我关于Android中所有可能的选项的详细文章
Java中字符串首字母大写的方法
public static String capitalizeString(String str) {
String retStr = str;
try { // We can face index out of bound exception if the string is null
retStr = str.substring(0, 1).toUpperCase() + str.substring(1);
}catch (Exception e){}
return retStr;
}
在KOTLIN中首字母大写的方法
fun capitalizeString(str: String): String {
var retStr = str
try { // We can face index out of bound exception if the string is null
retStr = str.substring(0, 1).toUpperCase() + str.substring(1)
} catch (e: Exception) {
}
return retStr
}
你要做的可能是:
s1 = name.substring(0, 1).toUpperCase() + name.substring(1);
(将第一个字符转换为大写,并添加原始字符串的其余部分)
此外,您创建了一个输入流读取器,但从不读取任何行。因此name将始终为空。
这应该可以工作:
BufferedReader br = new InputstreamReader(System.in);
String name = br.readLine();
String s1 = name.substring(0, 1).toUpperCase() + name.substring(1);