java - 递归和 if-else 语句

标签 java if-statement recursion

我是编程新手。我试图使用递归和 if-else 语句仅打印 99 瓶啤酒的歌词。这是我的代码。我怎样才能更好地打印歌词。

方法countdown打印歌词,同时 countdownB 应该打印从 99 一直到零的数字。

public static void countdown(int n) {   
    if (n== 0) {
        System.out.println("no beers");
    } else {
        System.out.println("more beers");
        countdown(n-1);
    }
}

public static void countdownB(int x) {   
    if (x==0){
        System.out.print("");
    } else {
        System.out.print(x);
        countdownB(x-1);
    }
}

public static void main(String[] args) {
    countdownB(3);
    countdown(3);
}

最佳答案

您可以将两个 countdown 方法合并为一个方法。

public static void countdown(int x) {   
    if (x == 0) {
        System.out.println("no beers");
    } else {
        // Print the number first and then the lyric
        System.out.println(x + " more beers");
        countdown(x-1);
    }
}

当你想打印 99 首歌词时,你应该调用它。

countdown(99);

关于java - 递归和 if-else 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44227959/

相关文章:

python - 显示 "if any"检测到的列表元素

java - 如何删除二叉树的叶子?

java - 从网页中获取所有超链接并在java中递归地执行此操作

java dom 转义字符

java - 无法将 Android Studio 与 Maven 存储库同步

javascript - If/Else 语句不计算

c - 查看 IF 条件代码以节省 CPU 周期

c - C语言169算法

java - 如何在 Java 中获取 Activity 连接的打印机?

java - 用于实现通用接口(interface)的 2 个以上类的高级 Java 习惯用法