Java:重复(理解代码)
有人能解释一下回程线是怎么工作的吗? 多谢各位Java:重复(理解代码),java,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
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));
}
}
公共类JavaApplication1{
/**
*重复字符串str次。
*@param str要重复的字符串
*@param times重复str次时间
*@return生成的字符串
*/
公共静态字符串重复(字符串str,int次){
返回新字符串(新字符[次])。替换(“\0”,str);
}
公共静态void main(字符串[]args){
System.out.println(重复(“*”,5));
}
}
构造函数字符串(char[]值)
分配新字符串,使其表示当前包含在字符数组参数中的字符序列
不确定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));
}
}
公共类JavaApplication1{
/**
*重复字符串str次。
*@param str要重复的字符串
*@param times重复str次时间
*@return生成的字符串
*/
公共静态字符串重复(字符串str,int次){
String sampleString=新字符串(新字符[次])。替换(“\0”,str);
返回样本串;
}
公共静态void main(字符串[]args){
System.out.println(重复(“*”,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("*****")
}
从内到外取if:
newchar[times]
创建一个大小为times
的字符数组,在调用repeat
时传入一个整数值。然后,replace
方法用str
参数替换字符数组中出现的每一个空值,该参数在您的情况下是星号。由于默认情况下,新字符数组使用空字符\0
初始化,因此会对数组中的每个元素进行替换。运行程序时,应该会得到一个由5个星号组成的字符串。您不清楚此代码的哪一部分?你知道什么是课堂吗?你知道什么是构造函数或方法吗?你读过所用构造函数/方法的文档吗?@Pshemo你读过我的问题吗?@Pshemo我不是在问类、构造函数或方法。是的,我读过你的问题,我仍然不知道你不清楚哪一部分<代码>返回新字符串(新字符[次])。替换(“\0”,str)代码>是嵌套和链接的一组指令,它们不是很复杂newchar[times]
已清除,它将创建大小为的新字符数组。所有新数组都填充了一些默认值,对于char,默认值是\0
(这在教程中很容易找到)<代码>新字符串(charArray)
使用数组创建字符串replace(what,replacement)
似乎也不清楚,但我可能错了,所以请告诉我哪一步让你感到困惑。@Pshemo特别是你刚才回答的我不清楚。问题似乎很清楚。谢谢你的回答,我在这里没有看到构造器repeat
是一种方法。String sampleString=new String(new char[times])。replace(“\0”,str);这是一个呼叫CoStructor感谢你,下面的答案已经解释了char[]包含的内容感谢你的帮助,这是让我困惑的部分