簡體   English   中英

Java ArrayList IndexOutOfBoundsException索引:1,大小:1

[英]Java ArrayList IndexOutOfBoundsException Index: 1, Size: 1

我正在嘗試用Java讀取某個文件並將其轉換為多維數組。 每當我從腳本中讀取一行代碼時,控制台會說:

Caused by: java.lang.IndexOutOfBoundsException: Index: 1, Size: 1

我知道這個錯誤是在編碼無法達到特定索引時引起的,但我現在還不知道如何修復它。

這是我編碼的一個例子。

int x = 1;
while (scanner.hasNextLine()) {
  String line = scanner.nextLine();
  //Explode string line
  String[] Guild = line.split("\\|");
  //Add that value to the guilds array
  for (int i = 0; i < Guild.length; i++) {
    ((ArrayList)guildsArray.get(x)).add(Guild[i]);
    if(sender.getName().equals(Guild[1])) {
      //The person is the owner of Guild[0]
      ownerOfGuild = Guild[0];
    }
  }
  x++;
}

**文字文件**

Test|baseman101|baseman101|0|
Test2|Player2|Player2|0|

其他解決方案,例如在此處找到的解決方案: 寫入文本文件而不用Java覆蓋

提前致謝。

問題1 - > int x = 1;
解決方案:x應該從0開始

問題2->

((ArrayList)guildsArray.get(x)).add(Guild[i]);

你正在增加x所以if x >= guildsArray.size()那么你將獲得java.lang.IndexOutOfBoundsException

if( x >= guildsArray.size())
      guildsArray.add(new ArrayList());
for (int i = 0; i < Guild.length; i++) {
    ((ArrayList)guildsArray.get(x)).add(Guild[i]);
    if(sender.getName().equals(Guild[1])) {
      //The person is the owner of Guild[0]
      ownerOfGuild = Guild[0];
    }
  }

問題出現在這里:

... guildsArray.get(x) ...

但是在這里引起:

int x = 1;
while (scanner.hasNextLine()) {
   ...

因為集合和數組是從零開始的(第一個元素是索引0 )。

試試這個:

int x = 0;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM