我一直在摆弄这段代码,并且无法弄清楚如何创建和添加到数组而不导致某种错误。这是我最接近让它工作的地方。
我已经尝试在我的第一个循环中创建数组,但我需要稍后在程序中访问它。
String userInput;
int i=0;
String damages [] = new String [i];
double repairCost [] = new double [i];
int j=0;
String infringements [] = new String [j];
double fines [] = new double [j];
double repairCostTotal = 0.00;
double finesTotal = 0.00;
double finalHire = 0.00;
do
{
System.out.print("Damage: D, Infringements: F, "Exit: X");
userInput = stdin.readLine();
if (userInput.equalsIgnoreCase("D"))
{
System.out.println("Damage description:");
damages[i] = stdin.readLine(); //<<<<--line of error
System.out.println("Repair Costs:");
repairCost [i] = Double.parseDouble(stdin.readLine());
repairCostTotal = repairCostTotal + repairCost [i];
i=i+1;
}
else if (userInput.equalsIgnoreCase("F"))
{
System.out.println("Infringement type:");
infringements[j] = stdin.readLine();
System.out.println("Fine:");
fines [j] = Double.parseDouble(stdin.readLine());
finesTotal = finesTotal + fines [j];
j=j+1;
}
else if (!userInput.equalsIgnoreCase("X"))
{
System.out.print("Enter a valid Selection:");
}
}
while (!userInput.equalsIgnoreCase("x"));
System.out.println("Damage Repair Details: ");
for ( i= 0; i < damages.length; i++)
System.out.println("- " + damages [i] + " ($" + repairCost[i] + ")");
System.out.printf("Damage Repair Total: %10.2f %n", repairCostTotal);
System.out.println("Traffic Infringement Details:");
for (j= 0; j < fines.length; j++)
System.out.println("- " + infringements [i] + " ($" + fines[j] + ")");
System.out.printf("Traffic Fine Total: %10.2f %n", finesTotal);
我收到此错误
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at CarHire.main(CarHire.java:106)
我确定这是我缺少的一个简单原则,感谢您提供任何帮助。