对不起,谈到这个问题我有点无能为力,我在程序的这个特定部分遇到了一些麻烦。
目标是,当有人输入三个字符串时,重新排列它,使“Emma Charlotte Leonard”成为“Leonard,Emma,C”。
这是我到目前为止的具体方法:
public String lastFirst (String str)
{
Scanner keyboard = new Scanner(System.in);
System.out.println ("Enter your name");
String lastFirst = keyboard.nextLine();
String middleAndLast = lastFirst.substring(lastFirst.indexOf(" ")+ 1);
String last = middleAndLast.substring(middleAndLast.indexOf(" ") + 1);
String first = lastFirst.substring(0, lastFirst.indexOf(" "));
String middle = middleAndLast.substring(0, middleAndLast.indexOf(" "));
char middleInitial = middle.charAt(0);
return("\"" + last + ", " + first + ", " + middleInitial + "\"");
}
如果我没有提供足够的信息,我们将不胜感激。
答案 0 :(得分:1)
我相信这是你想要实现的目标:
public class RearrangeName{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println ("Enter your name");
String inputStr= keyboard.nextLine();
System.out.println(lastFirst(inputStr));
}
public static String lastFirst (String str){
String middleAndLast = str.substring(str.indexOf(" ")+ 1);
String last = middleAndLast.substring(middleAndLast.indexOf(" ") + 1);
String first = str.substring(0, str.indexOf(" "));
String middle = middleAndLast.substring(0, middleAndLast.indexOf(" "));
char middleInitial = middle.charAt(0);
return("\"" + last + ", " + first + ", " + middleInitial + "\"");
}
}
请参阅Demo here
答案 1 :(得分:0)
你想要输出" Leonard,Charlotte,L" 或" Leonard,Emma,C" 。 程序的当前输出是第二个选项。如果你想要第一个输出,那么你应该将middleInitial声明为 String middleInitial = last.charAt(0); 。
答案 2 :(得分:0)
尝试以下示例,它将返回" Emma Charlotte Leonard" as"伦纳德,夏洛特,L"
public class Example{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Example exp = new Example();
System.out.print("Enter your number : ");
System.out.println(exp.getName(input.nextLine()));
}
private String getName(String name){
String arr[] = name.split(" ");
return arr[2]+ ", "+arr[1]+", "+arr[2].substring(0, 1);
}
}