我正在制作一个程序,该程序将切换字符串的第一个和最后一个字母,但是当我运行它时,它只是将第一个字母替换为最后一个字母。

public static String swap(String String3) {
    //finds first & last letter of string
    String firstLetter =  String3.substring(0, 1);
    String lastLetter = String3.substring(String3.length() - 1);
    String a = String3.replace(firstLetter, lastLetter);
    String z = a.replace(lastLetter, firstLetter );
    return z;
public static void main(String[] args){
    System.out.print("Enter your swap string: ");
    Scanner scan = new Scanner(System.in);
    String String3 = scan.nextLine();
    System.out.println(swap(String3));
    }


谁能告诉我我在做什么错?

最佳答案

让我们看看问题的原因,然后看看我解决问题的方法。

问题

下面,我在注释中描述了swap方法的代码中的一些调试:

//considering String3 is equals to something like "a---z"
public static String swap(String String3) {
    System.out.println(String3);

    //this stores "a" value
    String firstLetter = String3.substring(0, 1);
    System.out.println("first: " + firstLetter);

    //this stores "z" value
    String lastLetter = String3.substring(String3.length() - 1);
    System.out.println("last: " + lastLetter);

    /*
    this replaces in the String3 source the character which is
    equals to firstletter (= "a" value) for lastLetter (= "z" value)

    the String3 field, which is "a-z" is turned to "z-z"

    Then, the final value stored is "z-z"
     */
    String a = String3.replace(firstLetter, lastLetter);
    System.out.println("a: " + a);

    /*
    this replaces in the String3 source the character which is
    equals to lastLetter (= "z" value) for firstLetter (= "a" value)

    the a field, which is "z-z" is turned to "a-a"

    Then, the final value stored is "a-a"
     */
    String z = a.replace(lastLetter, firstLetter);
    System.out.println("z: " + z);

    /*
    by returning the field z you only will get the same character
    at start and end.
     */
    return z;
}


解决问题

我建议使用one-liner方法解决此问题,该方法使用substring()方法替换字符。看一看:

/*
 * This avoid creating new fields and uses only the passed parameter.
 *
 * - First we set the FIRST character of the s value to the LAST
 * character of the parameter;
 *
 * - Second we concatenate this with a substring from s, which goes
 * from second character to the "semi last" (last previous);
 *
 * - Then we can add the FIRST character at the END.
 */
public static String swapFirstAndLast(String s) {
    return s.charAt(s.length() - 1) + s.substring(1, s.length() - 1) + s.charAt(0);
}

09-11 20:24
查看更多