2014-06-06 35 views
-12

鑑於代碼..爲什麼你不能只是粘貼方法,使其工作?

public class test { 
    public static void main (String args[]) { 



     endUp("Hleeloe"); 

    } 

    public static String endUp(String str) { 

     if (str.length() < 3) { 

      return str.toUpperCase(); 
      } 

      if (str.length() >= 3) { 

      String sub= str.substring(str.length()-3,str.length()); 
      String front = str.substring(0,str.length()-3); 
      sub.toUpperCase(); 
      System.out.println(front + sub); 
      System.out.println(front); 
      System.out.println(sub); 
      System.out.println(sub.toUpperCase()); 
      return front + sub.toUpperCase(); 


      } 

      return str; 

      } 

} 

控制檯:

Hleeloe 
Hlee 
loe 
LOE 

我想有sub.toUpperCase();將字符串「sub」轉換爲全部大寫字母。但它沒有奏效。你可以看到當我第一次打印出來的時候,它仍然是小寫字母。但是,當我包含sub.toUpperCase();在返回之前的System.out.println()中,它確實打印出控制檯內顯示的所有大寫字母。

這是爲什麼?我如何使它只與sub.toUpperCase()一起工作;部分?

+0

你閱讀的javadoc? –

+2

因爲字符串是不可變的 – Reimeus

+0

它可能會返回一個新的字符串,即它不會修改.place –

回答

3

String是不可改變的。所以,sub.toUpperCase()不會更改字符串內部。它只是返回你是大寫的新字符串值:

爲大寫sub,而分配subtoUpperCase()方法的結果,像這樣:

sub = sub.toUpperCase(); 

這樣一來,你返回一個新的大寫字符串。

1

.toUpperCase()不會修改它應用於的字符串。

你需要做的:

sub = sub.toUpperCase(); 
0

還有就是你的代碼修正,你不大寫的串子賦值...

public static void main(String args[]) { 
     endUp("Hleeloe"); 
    } 

public static String endUp(String str) { 
    if (str.length() < 3) { 
     return str.toUpperCase(); 
    } 
    if (str.length() >= 3) { 
     String sub = str.substring(str.length() - 3, str.length()); 
     String front = str.substring(0, str.length() - 3); 
     sub = sub.toUpperCase(); 
     System.out.println(front + sub); 
     System.out.println(front); 
     System.out.println(sub); 
     System.out.println(sub.toUpperCase()); 
     return front + sub.toUpperCase(); 
    } 
    return str; 
} 
+0

無需發表愚蠢的評論。我刪除了愚蠢的評論,只是爲了保持SO專業。 :-) –

相關問題