这是我的代码: 导入java.util.Scanner;
class namedisplay {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.println("Enter your name: ");
String name = input.nextLine();
String capital1 = name.substring(0).toUpperCase();
String capital2 = name.substring(5).toUpperCase();
System.out.println(capital1+capital2);
}
}
程序输出: 输入你的名字: 李安娜 安娜·莉莉
我希望程序只将名字和姓氏的首字母大写,例如 Anna Lee。
最佳答案
System.out.println("Enter your name: ");
String name = input.nextLine();
String newName = "";
newName += name.charAt(0).toUpperCase();
newName += name.substring(1, name.length());
System.out.println(newName);
要获取第一个字母并将其大写,请使用name.charAt(0).toUpperCase();
。
然后将其添加到 newName
中。
然后您想要将 name
中的剩余字母添加到 newName
中。您可以通过添加 name
子字符串
来实现这一点
name.substring(1, name.length()); // 1 mean the substring will start at the
// second letter and name.length means the
// substring ends with the last letter
关于java - java中如何将名字的第一个字母大写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19647730/