當編譯這個程序時,我得到一個「reformatName」方法的錯誤,因爲它「必須返回一個java.lang.String類型的結果」,我假設它已經返回了!該方法採用的每個路徑都會返回一個字符串。 (很抱歉,如果這是可怕的格式化/寫的;這是我第一次在這裏發帖。)Java 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;
}
我已經採取了修復壓痕的自由。一般來說,您應該避免使用製表符,因爲不同的環境使用不同數量的列。堆棧溢出使用4列選項卡,但Java標準需要8列選項卡,所以最好使用空格。我喜歡在vim中編寫我的代碼,展開標籤,然後在發佈代碼時將n-paste粘貼到Stack Overflow。 – 2013-05-10 00:46:20