簡體   English   中英

Java:重復(理解代碼)

[英]Java: Repeat (Understanding the code)

有人可以解釋一下回線的工作原理嗎? 謝謝

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));
        }

    }

如果將其逐步分解,則更容易遵循

// 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("*****")
}

構造函數 String(char [] value)分配一個新的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));
    }

}

從內到外看一下: new char[times]創建一個大小為times的字符數組,該整數是在調用中傳遞給repeat 然后, replace方法使用str參數(在您的情況下為星號)替換字符數組中每次出現的null值。 由於新字符數組默認情況下使用空字符\\0初始化,因此替換將針對數組中的每個元素進行。 運行該程序時,您應該獲得5個星號的字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM