[英]Repeating a string
I am very new to programming and I have to write a method and program for the following; 我对编程非常陌生,因此我必须为以下内容编写方法和程序; public static String repeat(String str, int n) that returns the string repeated n times.
public static String repeat(String str,int n)返回重复n次的字符串。 Example ("ho", 3) returns "hohoho" Here is my program so far:
示例(“ ho”,3)返回“ hohoho”这是到目前为止的程序:
public static void main(String[] args) {
// **METHOD** //
Scanner in = new Scanner(System.in);
System.out.println("Enter a string");
String str = in.nextLine();
System.out.println(repeat (str));//Having trouble with this line
}
// **TEST PROGRAM**//
public static String repeat(String str, int n)
{
if (n <= 0)
{
return ""//Having trouble with this line
}
else if (n % 2 == 0)
{
return repeat(str+str, n/2);
}
else
{
return str + repeat(str+str, n/2);
}
}
}
I made some changes to my code, but it still is not working 我对代码进行了一些更改,但仍然无法正常工作
public static void main(String[] args) {
// **METHOD** //
Scanner in = new Scanner(System.in);
System.out.println("Enter a string");
String str = in.nextLine();
int n = in.nextInt();
System.out.println(repeat(str,n));
}
// **TEST PROGRAM**//
public static String repeat(String str, int n)
{
if (n <= 0)
{
return "";
}
else if (n % 2 == 0)
{
return repeat(str+str, n/2);
}
else
{
return str + repeat(str+str, n/2);
}
}
}
You've missed a semi colon on the line you're having trouble with, it should be return "";
您已经在遇到问题的行中错过了半冒号,应该
return "";
and not return ""
而不
return ""
Also, the line System.out.println(repeat (str));
另外,行
System.out.println(repeat (str));
should have 2 arguments because you're repeat definition is: 应该有2个参数,因为重复的定义是:
public static String repeat(String str, int n)
As a further note, an easier function might be 进一步说明,可能更简单的功能是
public static String repeat(String str, int n) { if (n == 0) return ""; String return_str = ""; for (int i = 0; i < n; i++) { return_str += str; } return return_str; }
我很快注意到的两件事:您忘记了一个半列,而您对“ repeat”的调用与方法签名不匹配(您忘记了n)
You are not passing correct arguments while you calling the desired method. 调用所需方法时,没有传递正确的参数。
Call as repeat (str,k)
k
- should be an integer 称为
repeat (str,k)
k
应为整数
public static String repeat(String toRepeat, int n){
if(n==0){
return "";
}
return toRepeat+repeat(toRepeat,n-1);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.