1

所以我的任务是写一个名为 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 次。

有人可以帮我理解这段代码吗?

4

5 回答 5

1

您需要传入递减的值y

public static String repl(String word, int y) {
    if (y <= 0) {
        return null;
    } else {
        System.out.print(repl(word, y - 1));
    }

    return word;
}

这样,递归调用的每次迭代都会将计数降低 1,当它达到 0 时结束。

请注意,您可能希望wordy到达时返回0,因为它需要最后一次打印:

public static String repl(String word, int y) {
    if (y <= 0) {
        return word;
    } else {
        System.out.print(repl(word, y - 1));
    }

    return word;
}

例子

此时,请注意我们word无论如何都返回,这使得第一个if条件变得不必要。您的整个功能可以简化为:

public static String repl(String word, int y) {
    if (y > 0) System.out.print(repl(word, y - 1));

    return word;
}

当然,使用for循环可能更容易做到这一点,但我假设递归是您任务的一部分。

于 2013-11-07T02:33:57.820 回答
0

y内部任何地方都没有递减repl(String word, int y)

于 2013-11-07T02:34:33.713 回答
0

基本上这是你必须做的:

    string toPrint = "";
    for (int i=0; i<y; i++)
    {
        toPrint += word;
    }
    System.out.println(toPrint)

此 for 循环将“word”变量添加到空字符串所需的次数,然后您只需打印该变量。

除非你当然需要使用递归......

于 2013-11-07T02:35:36.507 回答
0
  1. 递减 y
  2. null 不是空字符串。尝试用''替换它。
于 2013-11-07T02:36:03.603 回答
0

您需要更改您的代码

System.out.print(repl(word, y));

System.out.print(repl(word, --y));

在您的代码中,值 y 不会更改。所以方法 repl 将无限递归。

于 2013-11-07T02:36:29.267 回答