Java - 从for循环返回信息

时间:2012-02-07 01:20:34

标签: java loops for-loop return

所以我想做的就是回复:

输入为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;
}

6 个答案:

答案 0 :(得分:1)

你的情况有误,应该是 i< n ,如:

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 :(得分: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会更有效率。

答案 2 :(得分:1)

为什么不使用StringUtils.repeat它会为你做同样的事情,所以你可以做到以下几点:

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

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

答案 3 :(得分:0)

0 >= 3条件永远不会满足。它应i < n。因为我从0开始,它应该是<而不是&lt; =

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

答案 4 :(得分:0)

循环条件i>=n可能应为i<=n

答案 5 :(得分:0)

您的循环结束条件是问题,将其更改为i&lt; Ñ

相关问题