Return 使用 while 循环从给定数组中求出最小数 Java

Return the minimum number from the given array using while loop Java

大家好。你好吗? =)

我是 Java 的新手,目前

我有一个任务是创建一个方法,它需要一个参数sum——要发出的金额,以及returns这个金额可以发出的最少纸币数量。

只能使用While循环。

我是用for循环实现的,但是我找不到我在while循环中出错的地方。 你能给我提示或建议吗? 谢谢!

public class ATM {

    public static int countBanknotes(int sum) {
        int[] notes = new int[] { 500, 200, 100, 50, 20, 10, 5, 2, 1 };
        int[] noteCounter = new int[9];
        int amount = 0;

        for (int i = 0; i < 9; i++) {
            if (sum >= notes[i]) {
                noteCounter[i] = sum / notes[i];
                sum -= noteCounter[i] * notes[i];
            }
        }
        for (int i = 0; i < 9; i++) {
            if (noteCounter[i] != 0) {
                amount += noteCounter[i];
            }
        }
        return amount;
    }

    public static void main(String[] args) {

        // 6 (500 + 50 + 20 + 5 + 2 + 1
        int sum = 578;
        System.out.print(ATM.countBanknotes(sum));
    }
}

while 循环

public class JustATest {

    public static int countBanknotes(int sum) {
        int[] notes = new int[] { 500, 200, 100, 50, 20, 10, 5, 2, 1 }; 
        int[] noteCounter = new int[9]; 
        int amount = 0; 
        int i = 0;  
        
        while ( i < 9 ) {
            if (sum >= notes[i]) {
                i++;
                noteCounter[i] = sum / notes[i];
                sum -= noteCounter[i] * notes[i];           
            }
        }
        while ( i < 9 ) {           
            if (noteCounter[i] != 0) {
                i++;
                amount += noteCounter[i];           
            }
        }
        return amount;
    }

    public static void main(String[] args) {

        // Should be 6 (500 + 50 + 20 + 5 + 2 + 1)
        int sum = 578;
        System.out.print(JustATest.countBanknotes(sum));
    }
}

您需要在第二个 while 循环中将 i 值重新初始化为 0

  1. 您必须每次都在 while 循环中执行 i++。否则你会陷入死循环。

  2. 您必须重置 i 才能进入下一个循环。所以不推荐一个迭代器i用于两个循环。

public static int countBanknotes(int sum) {
    int[] notes = new int[]{500, 200, 100, 50, 20, 10, 5, 2, 1};
    int[] noteCounter = new int[9];
    int amount = 0;
    int i = 0;

    while (i < 9) {
        if (sum >= notes[i]) {
            noteCounter[i] = sum / notes[i];
            sum -= noteCounter[i] * notes[i];
        }
        i++;
    }

    i = 0;
    while (i < 9) {
        if (noteCounter[i] != 0) {
            amount += noteCounter[i];
        }
        i++;
    }
    return amount;
}

您需要在循环之间重新初始化 i 变量,或使用另一个变量,例如 j.

此外,您不应该在 while 循环的 if 语句中包含 i++。否则,在某些情况下计数器永远不会递增,您将陷入无限循环。那很不好! 将 i++ 放在 if 语句之外的 while 循环底部,如下所示:

while ( i < 9 ) {
    if (sum >= notes[i]) {
        noteCounter[i] = sum / notes[i];
        sum -= noteCounter[i] * notes[i];           
    }
    i++;
}
int j = 0;
while ( j < 9 ) {           
    if (noteCounter[j] != 0) {
        amount += noteCounter[j];           
    }
    j++;
}

这样,无论如何计数器总是递增的,你不会死循环。 我也在上面的代码中修复了你的问题。