以下是要求: 一世。如果有第一个,中间个和最后一个,则只显示名字和姓氏 II。如果有第一个和最后一个,则显示第一个和最后一个 III。如果只有名字,则只显示
我有以下代码:
String fullName = "first middle last";
Scanner nameScanner = new Scanner(fullName);
nameScanner.findInLine(" ");
MatchResult result = nameScanner.match();
if(result.groupCount() > 2)
{
System.out.println(result.group(1)+ " "+ result.group(3));
}
else
{
System.out.println(fullName);
}
当我尝试运行代码时,我得到了
Exception in thread "main" java.lang.IllegalStateException: No match result available
at java.util.Scanner.match(Unknown Source)
at com.assignment.RunAssignmentApp.main(RunAssignmentApp.java:48)
我做错了什么?
答案 0 :(得分:1)
String
内置split()
。
String fullName = "first middle last";
String[] names = fullName.split(" ");
switch(names.length) {
case 3: // The string had three tokens. Print the first and last one.
System.out.println(names[0] + names[2]);
break;
case 2: // The string had two tokens. Print both.
System.out.println(names[0] + names[1]);
break;
case 1: // The string had one tokens. Print it.
System.out.println(names[0]);
break;
default: // The string had less than one or greater than 3 tokens.
System.out.println("You either have no name or a very long name!");
}
答案 1 :(得分:1)
扫描仪无法正常工作。你写这篇文章的方式,你最好根据空格将输入分成字符串数组:
public static void nameScanner() {
String fullName = "first middle last";
String[] names = fullName.split(" "); // split the string at the spaces
if (names.length > 2) {
System.out.println(names[0] + " " + names[2]); // arrays start at index 0, so names[0] is first name
} else {
System.out.println(fullName);
}
}
当然,如果您正在从用户那里获取输入,那么您肯定希望添加一些错误检查和处理,以确保您不会超出阵列的界限。
答案 2 :(得分:1)
尝试
nameScanner.findInLine("(\\w+) (\\w+) (\\w+)");