2014-10-06 152 views
-1

我想要姓氏打印与第一个字母只有大写,但我得到的所有姓氏大写。我希望用户输入他们的名字像乔丹托雷斯和回馈托雷斯,J.大写首字母的姓

import java.util.*; // for Scanner 

public class ProcessName { public static void main(String[] args) { String name; 
    Scanner console = new Scanner(System.in); 
    System.out.print("Type your name: "); //send to user 

    name = console.nextLine(); 
    String[] nameArray = name.split(" ");//split string into array 

    String firstName = name.valueOf(name.charAt(0)).toUpperCase(); //get first letter 
    String lastName = name.substring(name.indexOf(" ") + 1).toUpperCase(); 

    String myName = lastName + ", " + firstName;//give last and first name 

     System.out.println("Your name is: " + myName + "."); 

我的输出TORRES,J.

+0

那么,有什么问题呢?如果你不希望它是'TORRES',而是'Torres',那么只需要将'.toUpperCase()'应用到第一个字母,你就可以将它应用到整个子字符串中。 – 2014-10-06 02:07:25

+0

我只想把姓氏的第一个字母大写,而不是全部。 – Jordan 2014-10-06 02:09:37

+0

没问题,那么如果他们只把torres没有资本t呢?那么它只是托雷斯。我怎么能这样做,所以第一个字母总是大写的姓氏? – Jordan 2014-10-06 02:14:19

回答

2
// Get the last name as entered by the user 
String lastName = name.substring(name.indexOf(" ") + 1); 

// Upcase the first character, then append the remaining characters 
lastName = Character.toUpperCase(lastName.charAt(0)) + lastName.substring(1); 
+0

好吧,我的男人,非常感谢。那是我需要的。我现在知道了。 – Jordan 2014-10-06 02:26:42