CoinChangeProblem 代码中的异常
Exception in CoinChangeProblem code
导入java.io.*;
public class CoinChangeProblem {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
int[] arr;
arr = new int[]{1, 2, 5, 10, 20, 50, 100, 500, 1000};
int[] arr2;
arr2 = new int[]{-1, -1, -1, -1, -1, -1, -1, -1, -1};
int max_coin = 0, due, i = 0, j = 0;
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
System.out.print("\n\n\tEnter the amount of currency due");
due = Integer.parseInt(stdin.readLine());
while (due != 0) {
for (j = 0; due > arr[j] && j < 9; )
max_coin = arr[j++];
j = 0;
arr2[i] = max_coin;
due = due - max_coin;
i += 1;
}
i = 0;
for (int k = 0; arr2[k] != -1; k++) {
System.out.print(" " + arr2[k]);
}
}
}
编译器在第 9 行抛出 ArrayIndexOutOfBoundsException,23.If您有解决方案请帮忙!
for 循环的最后一次迭代使 arr2[i] = max_coin
访问 arr2[9]
但数组的最后一个索引是 8。
将循环更改为
for(j=0; j<9 && due>arr[j];)
max_coin=arr[j++];
Java 与短路一起工作,因此当您首先检查 j 是否小于 9 时,它将为假并且循环结束。
该程序从存储在 'due' 局部变量中的标准输入获取输入变量。它仅在 'due' 输入 <= 7 时起作用。如果输入值大于 7,则会引发此异常:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
at CoinChangeProblem.main(CoinChangeProblem.java:23)
注意'9'不是行号,它表示给定的索引大于数组的最大大小。 'attr2'数组大小为9,支持[0-8]个索引。因此,当 'i' 变量达到数字 9 时,'arr2[i]' 表达式会导致 ArrayIndexOutOfBoundsException。
导入java.io.*;
public class CoinChangeProblem {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
int[] arr;
arr = new int[]{1, 2, 5, 10, 20, 50, 100, 500, 1000};
int[] arr2;
arr2 = new int[]{-1, -1, -1, -1, -1, -1, -1, -1, -1};
int max_coin = 0, due, i = 0, j = 0;
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
System.out.print("\n\n\tEnter the amount of currency due");
due = Integer.parseInt(stdin.readLine());
while (due != 0) {
for (j = 0; due > arr[j] && j < 9; )
max_coin = arr[j++];
j = 0;
arr2[i] = max_coin;
due = due - max_coin;
i += 1;
}
i = 0;
for (int k = 0; arr2[k] != -1; k++) {
System.out.print(" " + arr2[k]);
}
}
}
编译器在第 9 行抛出 ArrayIndexOutOfBoundsException,23.If您有解决方案请帮忙!
for 循环的最后一次迭代使 arr2[i] = max_coin
访问 arr2[9]
但数组的最后一个索引是 8。
将循环更改为
for(j=0; j<9 && due>arr[j];)
max_coin=arr[j++];
Java 与短路一起工作,因此当您首先检查 j 是否小于 9 时,它将为假并且循环结束。
该程序从存储在 'due' 局部变量中的标准输入获取输入变量。它仅在 'due' 输入 <= 7 时起作用。如果输入值大于 7,则会引发此异常:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9 at CoinChangeProblem.main(CoinChangeProblem.java:23)
注意'9'不是行号,它表示给定的索引大于数组的最大大小。 'attr2'数组大小为9,支持[0-8]个索引。因此,当 'i' 变量达到数字 9 时,'arr2[i]' 表达式会导致 ArrayIndexOutOfBoundsException。