2012-02-07 100 views
0

所以我想要做的是回報:爪哇 - 從返回信息循環

輸入爲createMixedString(Hello,there,3)

,我想輸出HellothereHellothereHellothere

我的問題是,當它運行它只是回報Hellothere就好像程序沒有看到我在for循環中做的重新分配。

public static String createMixedString(String s1, String s2, int n) { 
    String result = s1+s2; 

    for (int i=0;i>=n;i++) { 
     result = result+s1+s2; 
    } 
    return result; 
} 
+1

檢查條件,我認爲你把「>」錯誤的方式。 – warbio 2012-02-07 01:23:54

回答

0

0 >= 3條件永遠不會滿足。它應該i < n。因爲我從0開始,它應該是不< = <

for (int i=0;i<n;i++) {  
    result = result+s1+s2; 
    }  
0

也許循環條件i>=ni<=n

1

您的情況是錯誤的,它應該是我<ñ爲:

public static String createMixedString(String s1, String s2, int n) { 
    String result = s1+s2; 

    for (int i=0; i < n; i++) { 
     result = result+s1+s2; 
    } 
    return result; 
} 
1

考慮以下幾點:

public static String createMixedString(String s1, String s2, int n) { 
     StringBuilder s = new StringBuilder(); 
     for (int i = 0; i < n; i++) { 
      s.append(s1); 
      s.append(s2); 
     } 
     return s.toString(); 
    } 

注意,在條件檢查檢查,看是否i仍然小於n,而不是檢查,而i >= n,這是沒有意義的。另外,如果串聯字符串,則使用StringBuilder會更加高效。

0

你的循環結束條件的問題,將其更改爲我<ň

1

爲什麼不使用StringUtils.repeat它會做同樣的事情給你,讓你可以做到以下幾點:

public static String createMixedString(String s1, String s2, int n) { 
    String result = s1 + s2; 
    return StringUtils.repeat(result, n); 
} 

這應該以你想要的方式工作