繁体   English   中英

从文本文件填充时数组索引越界错误

[英]Array Index Out of Bounds Error While Populating From a Text File

我在尝试从文本文件填充数组时遇到此错误。 我认为这可能与我的if循环有关,但我真的不确定。 它给了我myData[9]上的越界错误。 我想要做的是检查第一个字母是否是D (意味着下面的东西是更新),然后创建一个更新对象。 我的update.txt文件中只有 10 个东西可以用来填充myData ,这就是为什么我很困惑为什么myData[9]给我一个越界错误(特别是我试图将它设置为等于lastThirty )。

scan = new Scanner(file);
while (scan.hasNext())
{
    String str = scan.nextLine();
    String[] myData = str.split("#");
    if (myData[0].equalsIgnoreCase("D"))
    {
        recordType = myData[0];
        actionCode = myData[1];
        boxID = Integer.parseInt(myData[2]);
        movieID = Integer.parseInt(myData[3]);
        movieTitle = myData[4];
        movieGenre = myData[5];
        releaseYear = myData[6];
        inStock = myData[7];
        totalRentals = Integer.parseInt(myData[8]);
        lastThirty = Integer.parseInt(myData[9]);
        updates[count] = new UpdateRecord(recordType, actionCode, boxID, movieID, movieTitle, movieGenre, releaseYear, inStock, totalRentals, lastThirty);
        count++;
    }

文件内容如下:

 H#Title Town Video Mart Updates#04\24\2016
 D#A#4#5#Harry Potter#Action#2001#True#50#5
 D#A#4#5#Shutter Island#Suspense#2001#True#50#5
 D#A#4#5#The Blind Side#Drama#2001#True#50#5
 D#A#4#5#Borat#Comedy#2001#True#50#5
 D#A#4#5#Bad GrandPa#Comedy#2001#True#50#5
 T#Title Town Video Mart Updates#04\24\2016#5

这取决于 txt 的编写方式,但可能是String[] myData = str.split("#"); 仅返回一个长度为 9 的数组,因此访问第 10n 个元素会导致错误。

例如,考虑“boo#and#foo”应该返回一个字符串[3]。 您的 txt 功能应该返回一个字符串 [10]。

尝试修改 txt 以添加另一个 '#' 并查看它是否有效,或者更好地在调试中查看数组的内容。

暂无
暂无

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

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