gpt4 book ai didi

java - 数组越界>

转载 作者:行者123 更新时间:2023-11-30 01:41:16 25 4
gpt4 key购买 nike

我需要创建一个程序来计算您将收到的变化,但它说:

线程“main”中的异常java.lang.ArrayIndexOutOfBoundsException:索引9 长度 5 出界 在 Main.main(Main.java:34)

我对在 Java 中使用数组还很陌生,所以任何指针都会有帮助

import java.math.*;

public class Main {

static int changeTotal, penny, nickel, dime, quarter, dollarBill, fiveBill, tenBill, twentyBill, fiftyBill, hundredBill;
static double payed, price;

public static void main(String args[]) {

Scanner myScan = new Scanner(System.in);

System.out.println("Enter cost of item");
price = myScan.nextDouble();
System.out.println("Enter money given");
payed = myScan.nextDouble();

int priceInt = (int) (price * 100);
int payedInt = (int) (payed * 100);

penny = 1;
nickel = 5;
dime = 10;
quarter = 25;
dollarBill = 100;

int[] currencyArray = {penny, nickel, dime, quarter, dollarBill};
int[] changeCount = {0, 0, 0, 0, 0};
if(payed > price) {
changeTotal = payedInt - priceInt;
}

for(int i = 9; i >= 0; i--) {
int remainder = (changeTotal % currencyArray[i]);
if(remainder < changeTotal) {
changeCount[i] = (changeTotal - remainder) / currencyArray[i];
changeTotal = remainder;
}
}

System.out.println(payed - price);
System.out.println("Ones: " + changeCount[4]);
System.out.println("Quarters: " + changeCount[3]);
System.out.println("Dimes: " + changeCount[2]);
System.out.println("Nickels: " + changeCount[1]);
System.out.println("Pennies: " + changeCount[0]);
}
}

最佳答案

为了补充之前的答案,我建议使用对数组长度的引用,而不是硬连接该值。处理这样的情况可能是一个不错的做法,在这种情况下,您使用 for 循环来迭代数组,因为从那时起,如果数组将来由于某种原因发生变化,您不必跟踪硬编码值来调整它。例如,类似 for(int i =currencyArray.length - 1; i >= 0; i--) 的内容。

关于java - 数组越界>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59887529/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com