java - 我怎样才能让它重复呢?

标签 java

所以我的作业要求编写一个名为 repl 的方法,该方法接受一个字符串和多次重复作为参数,并返回连接多次的字符串。例如,调用 repl("hello", 3) 应返回 “你好你好你好”。如果重复次数为零或更少,则该方法应返回空字符串。

这是我编写的代码之一。

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 次。

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

最佳答案

您需要传入 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 时结束。

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

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

    return word;
}

Example

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

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

    return word;
}

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

关于java - 我怎样才能让它重复呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19826927/

相关文章:

java - 分析Java项目中的JAR依赖

java - 如何在Android中保存图像而不压缩?

java - 在运行时使用 IntelliJ IDEA 调试器在整个 JVM 中搜索值

java - 为什么我的位图排序没有比我的归并排序快无限?

java - 如何避免 Firefox 中的窗口下载​​弹出窗口使用 Java selenium?我需要自动下载而不询问弹出窗口吗?

java - Json 和抽象类 'Can not construct instance'

java - Hibernate多对多保存

java - 如何将日期转换为毫秒

java - 使用静态内部类如何避免内存泄漏?

java - 单击通知后从后台打开应用程序后运行函数