递归方法接受两个参数:一个字符串S和一个intñ
(其实我不知道如何写这个代码,我查了一下网上找到它也许是这样,但是当我运行它,它没有工作。递归方法接受两个参数:一个字符串S和一个intñ
例如输入(“College”,2),应该输出(“College”,“College”),但是显示无法读取 我只是不知道该如何解决这个问题 请教我如何编写代码
-------编写一个名为printStr的RECURSIVE方法,该方法接受两个参数:一个String和一个int n。该方法应该返回一个包含字符串s的字符串s次,每次用空格隔开,假设n> = 1.
例如,调用printStr(“Lehman”,2)应返回“Lehman Lehman”,并调用printStr(“The Bronx”,4)应返回“The Bronx The Bronx The Bronx The Bronx”。
打电话给班级家庭作业5_2。在主要方法中,多次调用您的方法printStr来测试它。
进口java.util.Scanner的;
公共类Homework5_2 {
public static void main(String[] args) {
Scanner keyboard=new Scanner(System.in);
int n = 0;
String s = args[1];
System.out.print(printStr(s,n));
}
public static String printStr(String s, int n){
if (n==0) {
return "";
}
return s + printStr(s, n - 1);
}
夫妇与你的代码的问题。引用赋值,因为你的贴吧:
"separated by a space"
"Assume n >= 1"
"In the main method, call your method printStr several times to test it."
所以,写main()
显式调用,不要使用args
。添加缺少的空间,不要打电话或检查0
:
public static void main(String[] args) {
System.out.println('"' + printStr("College", 2) + '"');
System.out.println('"' + printStr("Lehman", 2) + '"');
System.out.println('"' + printStr("The Bronx", 4) + '"');
}
public static String printStr(String s, int n) {
if (n == 1)
return s;
return s + ' ' + printStr(s, n - 1);
}
加引号('"'
)以println()
,以确保没有添加多余的空格。
输出
"College College"
"Lehman Lehman"
"The Bronx The Bronx The Bronx The Bronx"
非常感谢你!那很好! –
好了,把你的功课。但如果你会更努力地自己做点什么,那会更好。
static int maxn;
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
String s = scanner.next();
maxn = scanner.nextInt();
System.out.print(printStr(s, 0));
}
public static String printStr(String s, int n){
if(n == maxn){
return "";
} else if (n != 0){
s = " " + s;
}
return s + printStr(s, n + 1);
}
我应该把这个n值放在哪里? –
@LiXiaolong检查编辑 – serhii
当我运行它时,它显示*线程“主”java.lang.ArrayIndexOutOfBoundsException异常:1 \t在Homework5_2.main(Homework5_2.java:9) –
不知道什么是错与您的代码...只是didnt把一个空间..
public static String printStr(String s, int n) {
if (n == 1) {
return s;
}
return s + " " + printStr(s, n - 1);
}
这也有帮助,但它仍然不起作用。谢谢! –
从字符串s = args [1]; to String s = args [0];如果你在eclipse中运行,右键点击.java文件。运行 - 运行配置,进入参数选项卡并在“程序参数”部分中输入一个单词 –
我不熟悉配置。 –
添加空间,并在最后一个字符串的给换行。
public static String printStr(String s, int n){
if (n==0) {
return "\n";
}
return s+" " + printStr(s, n - 1);
}
你在处理什么问题? –
为了让回答者或其他有类似问题的人更容易,请编辑添加一个特定的问题陈述 - “不起作用”可以假定,但* how *不起作用?什么错误信息或不正确的行为是特征? –