System.out.println()在递归函数内部不起作用

时间:2014-09-27 16:11:56

标签: java recursion

这是我写的Java代码(逻辑是你可以得到一个免费的汽水瓶,如果你交换5个空汽水瓶)。随意批评或反馈更好的方法。

package com.eanurag.practice;

import java.util.Scanner;

public class SodaBottleProblem {

    private int totalSodaBottle = 0;
    private int freeSodaBottle = 0;
    private int remainingBottle = 0;

    public int numberOfBottles(int originalNumberOfBottles) {
        freeSodaBottle = originalNumberOfBottles;
        while (freeSodaBottle % 5 >= 5) {
            if (freeSodaBottle % 5 == 0) {
                freeSodaBottle = freeSodaBottle / 5;
                System.out.println("The Free Bottle count now is: "
                        + freeSodaBottle);
                totalSodaBottle = totalSodaBottle + freeSodaBottle;
                System.out.println("The total Bottle count now is: "
                        + totalSodaBottle);
                numberOfBottles(freeSodaBottle);
            }

            else if (originalNumberOfBottles % 5 != 0) {
                remainingBottle = freeSodaBottle % 5;
                System.out
                        .println("The remaining count is: " + remainingBottle);
                freeSodaBottle = freeSodaBottle - (remainingBottle);
                System.out.println("The Free Bottle count now is: "
                        + freeSodaBottle);
                numberOfBottles(freeSodaBottle);
            }
        }
        totalSodaBottle = totalSodaBottle + (freeSodaBottle + remainingBottle)
                / 5;
        System.out.println("Final value before return is:" + totalSodaBottle);
        return totalSodaBottle;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        SodaBottleProblem sd = new SodaBottleProblem();
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the original number of Soda bottles");
        int originalNumberOfBottles = sc.nextInt();
        System.out.println("Total number of bottles you can get: "
                + sd.numberOfBottles(originalNumberOfBottles));
        sc.close();
    }

}

问题:我很难理解为什么System.out.println()调用内部递归方法 numberOfBottles 根本不起作用。这是控制台中的输出

Enter the original number of Soda bottles
77
Final value before return is:15
Total number of bottles you can get: 15

3 个答案:

答案 0 :(得分:2)

while (freeSodaBottle % 5 >= 5)

此行始终为false,模B总是小于B

答案 1 :(得分:1)

你必须修复你的代码,int modulo 5永远不能大于或等于5所以永远不会输入while循环

答案 2 :(得分:0)

条件(freeSodaBottle%5> = 5)将始终为false