Java:重复(理解代码)

时间:2015-07-05 14:51:25

标签: java

有人可以解释一下返回线是如何工作的吗? 谢谢

public class JavaApplication1 {
        /**
         * Repeat string <b>str</b> <b>times</b> time.
         * @param str string to repeat
         * @param times repeat str times time
         * @return generated string
         */
        public static String repeat(String str, int times) {
            return new String(new char[times]).replace("\0", str);
        }
        public static void main(String[] args) {
            System.out.println(repeat("*", 5));
        }

    }

3 个答案:

答案 0 :(得分:2)

如果逐步分解

,则更容易理解
// str = "*" and times = 5
public static String repeat(String str, int times) {
  //we crete a new empty array which will have values {'\0','\0','\0','\0','\0'}
  char[] charArray = new char[times](); 
  String newstr = new String(charArray); // newstr.equals("\0\0\0\0\0")
  newstr = newstr.replace('\0', str); //we now replace all '\0' with "*"
  return newstr; //newstr.equals("*****")
}

答案 1 :(得分:1)

构造函数字符串(char []值)   分配一个新的String,使其表示当前包含在字符数组参数中的字符序列。

不确定代码中包含的char []是什么以及实际上您打算做什么。 return方法也可以按如下方式完成,这可能会让你理解。

这类似于

public class JavaApplication1 {
    /**
     * Repeat string <b>str</b> <b>times</b> time.
     * @param str string to repeat
     * @param times repeat str times time
     * @return generated string
     */
    public static String repeat(String str, int times) {
        String sampleString=new String(new char[times]).replace("\0", str);
        return sampleString;
    }
    public static void main(String[] args) {
        System.out.println(repeat("*", 5));
    }

}

答案 2 :(得分:1)

从内到外取出:new char[times]创建一个大小为times的字符数组,这是在调用repeat时传入的整数值。然后,replace方法将字符数组中每个出现的空值替换为str参数,在您的情况下为星号。由于默认情况下使用空字符\0初始化新字符数组,因此会对数组中的每个元素进行替换。运行程序时,您应该得到一个包含5个星号的字符串。