繁体   English   中英

创建一个未知长度的数组

[英]Creating an array of unknown length

我一直在摆弄这段代码,并且无法弄清楚如何创建和添加到数组而不会导致一种或另一种错误。 这是我最接近使其正常工作的地方。

我尝试在第一个循环中创建数组,但是稍后需要在程序中访问它。

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)

我确信这是我所缺少的简单原则,我们将不胜感激。

使用Java ArrayList创建动态大小的数组。

查看此文档

您的问题是您要创建一个长度为0的数组,这意味着您不能在其中放入任何内容。 然后,您尝试将某些内容放在索引0处。

其次,没有“未知”大小的数组。 在创建数组时总是知道大小。 如果需要动态数组,则需要使用ArrayList或其他Collection

问题是您使用初始化为大小0的数组-您的代码:

int j=0;
String infringements [] = new String [j];
double fines [] = new double [j];

您必须将其初始化为输入的大小(即j > 0 )或使用具有动态大小的List ,以防您不知道前面的输入大小。

int j=0;
String infringements [] = new String [j];

您正在创建大小为0的数组...

如果您不知道大小,请使用ArrayList之类的列表

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM