如何编写一个java程序来接受一个人的全名并输出带有首字母的姓氏?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30284912/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to write a java program to accept the full name of a person and output the last name with initials?
提问by coder123
I've written the following code. This works if only there are two initials before last name. How do i modify it to work with 3 or more initials. For example:
我已经编写了以下代码。如果姓氏前只有两个首字母,则此方法有效。我如何修改它以使用 3 个或更多首字母。例如:
Input: ABC EFG IJK XYZ
Input: ABC EFG IJK XYZ
Output I want is: A E I XYZ
Here is my code:
这是我的代码:
import java.util.*;
class Name{
public static void main(String[] args){
System.out.println("Please enter a Firstname , MiddleName & Lastname separated by spaces");
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
System.out.println(name);
String[] arr = name.split(" ",3);
System.out.println(arr[0].charAt(0)+" "+arr[1].charAt(0)+" "+arr[2]);
}
}
采纳答案by Eran
Use a loop and don't limit the split to 3 :
使用循环并且不要将拆分限制为 3 :
{
System.out.println("Please enter a Firstname , MiddleName & Lastname separated by spaces");
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
System.out.println(name);
String[] arr = name.split(" ");
// print all the initials
for (int i = 0; i < arr.length - 1; i++) {
System.out.print(arr[i].charAt(0) + " ");
}
// print the last name
System.out.println(arr[arr.length-1]);
}
回答by Eran
import java.util.*;
class SName
{
public static void main(String[] args)
{
String n;
Scanner c=new Scanner(System.in);
System.out.print("Enter the user name:");
n=c.nextLine();
String [] t=n.split(" ");
int l=t.length;
System.out.print("Your Short name:");
for(int i=0;i<l-1;i++)
{
System.out.print(t[i].charAt(0)+".");
}
System.out.print(t[l-1]);
}
}
Try This code
More Java Program
试试这个代码
更多Java 程序