簡體   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