2012-02-07 98 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); 
} 

这应该以你想要的方式工作