编译这个程序时,我收到“reformatName”方法的错误,因为它“必须返回 java.lang.String 类型的结果”我假设这是它已经返回的内容!该方法采用的每条路径,最终都会返回一个字符串。(对不起,如果这是可怕的格式/编写;这是我第一次在这里发帖。)
import java.util.*;
public class NameFormatChallenge {
public static void main(String[] args) {
Scanner wordInput = new Scanner(System.in);
System.out.println("Enter a name");
String userInput = wordInput.nextLine();
String[] name = userInput.split(" ");
System.out.println(reformatName(name));
}
public static String reformatName(String[] name) {
if(name[1].charAt(1)=='.')
return formatOne(name);
else if(name[1].length()==1)
return formatTwo(name);
else if(name[0].charAt(name[0].length()-1)!=',')
return formatThree(name);
else if(name[2].length()>2)
return formatFour(name);
else if(name[2].charAt(name[2].length()-1)=='.')
return formatFive(name);
else if(name[2].length()==1)
return formatSix(name);
}
public static String formatOne(String[] name) {
name[1] = name[1].substring(0,1);
String tempZero = name[0];
String tempOne = name[1];
String tempTwo = name[2];
name[0] = tempTwo;
name[1] = tempZero;
name[2] = tempOne;
return nameConcatenation(name);
}
public static String formatTwo(String[] name) {
String tempZero = name[0];
String tempOne = name[1];
String tempTwo = name[2];
name[0] = tempTwo;
name[1] = tempZero;
name[2] = tempOne;
return nameConcatenation(name);
}
public static String formatThree(String[] name) {
String tempZero = name[0];
String tempOne = name[1];
String tempTwo = name[2];
name[0] = tempTwo;
name[1] = tempZero;
name[2] = tempOne;
return nameConcatenation(name);
}
public static String formatFour(String[] name) {
String tempOne = name[1];
String tempTwo = name[2];
name[1] = tempTwo;
name[2] = tempOne;
return nameConcatenation(name);
}
public static String formatFive(String[] name) {
name[2] = name[2].substring(0,1);
String tempOne = name[1];
String tempTwo = name[2];
name[1] = tempTwo;
name[2] = tempOne;
return nameConcatenation(name);
}
public static String formatSix(String[] name) {
String tempOne = name[1];
String tempTwo = name[2];
name[1] = tempTwo;
name[2] = tempOne;
return nameConcatenation(name);
}
public static String nameConcatenation(String[] name) {
StringBuilder b = new StringBuilder();
int endOfArrZero = name[0].length()-1;
int endOfArrOne = name[1].length();
int endOfArrTwo = name[2].length()+1;
for (int i = 0; i<3; i++) {
b.append(String.valueOf(name[i]));
if(i!=2) {
b.append(" ");
}
}
if(b.charAt(endOfArrZero) != ',') {
b.insert(endOfArrZero,",");
endOfArrOne=endOfArrOne+1;
endOfArrTwo=endOfArrTwo+1;
}
if(b.charAt(endOfArrOne) == '.') {
b.deleteCharAt(endOfArrOne);
endOfArrTwo=endOfArrTwo-1;
}
String Finalname = b.toString();
return Finalname;
}