所以我的任务是写一个名为 repl 的方法,它接受一个字符串和多次重复作为参数,并返回多次连接的字符串。例如,调用 repl("hello", 3) 应该返回 "hellohellohello"。如果重复次数为零或更少,则该方法应返回一个空字符串。
所以这是我写的代码之一。
import java.util.Scanner;
public class Hello {
public static void main (String [] args){
Scanner console = new Scanner (System.in);
System.out.println("Enter the word");
String word = console.next();
System.out.println("Enter the number");
int y = console.nextInt();
repl(word, y);
}
public static String repl(String word, int y) {
if (y <= 0) {
return null;
}else {
System.out.print(repl(word, y)); //line 21, error is here
}
return word;
}
}
目前这段代码正在编译,但是当我运行它时,它会打印出来
at Hello.repl(Hello.java:21)
一遍又一遍地。
我还写了一个 for 代码,它只会打印出单词一次。我已经为此工作了大约一个小时,但我仍然很困惑如何让这个词重复 y 次。
有人可以帮我理解这段代码吗?