我正在尝试创建一个Java程序,该程序将使用输入量并以最少的硬币输出找零。尽管在运行程序时可以获得所需的输出,但是对于Change方法却遇到了单元测试错误。这是我的代码:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int totalamount;
int[] coins = new int[] { 100, 25, 10, 5, 1 };
Scanner s = new Scanner(System.in);
totalamount = s.nextInt();
Change(totalamount, coins);
}
public static void Change(int totalamount, int[] coins) {
int[] amount = new int[5];
for (int i = 0; i < 5; i++) {
if (totalamount >= coins[i]) {
amount[i] = totalamount / coins[i];
totalamount = totalamount % coins[i];
}
}
for (int i = 0; i < 5; i++) {
if(amount[i] != 0)
System.out.println(amount[i]);
}
}
}
这是我得到的单元测试错误:
Change(300, coins)
Your output
java.lang.ArithmeticException: / by zero
答案 0 :(得分:2)
coins [i]在某些时候必须为零。检查您的数据。为了保障安全,请多加一张硬币支票[i]
if (coins[i] > 0 && totalamount>= coins[i]) {
...
}