java - 有关 ArrayIndexOutOfBoundsException 的问题吗?

标签 java arrays indexoutofboundsexception throws

所以我有这段代码......这就是它的一部分的样子。

File File = new File("data2.txt");
    Scanner readUpdate = new Scanner(File);
    Player[] updatePlayers = new Player[200];
    String updateSTR;
    int updateTotalCounter = 0;
    while (readUpdate.hasNext()) {

        updateSTR = readUpdate.nextLine();
        String [] updateData = updateSTR.split(",");
        updatePlayers[updateTotalCounter] = new Player(updateData[0], updateData[1],updateData[2], 
                Integer.parseInt(updateData[3]), Integer.parseInt(updateData[4]));

        updateTotalCounter++;

    }

    readUpdate.close();

Java 不断出现并告诉我

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
    at Main.main(Main.java:43)

我不明白这是什么意思。有什么线索吗??

最佳答案

这意味着您正在尝试访问数组中大于数组中元素数量的位置,因此您会遇到常见的异常。

您假设数组 updateData 对于您读取的每一行都有 5 个位置,而对于至少其中一行来说这似乎是错误的,因此会引发异常。

确保

String [] updateData = updateSTR.split(",");

所有行的大小都是 5(从 0 到 4)。通过这种方式修复问题,但请注意某些行将不会被处理:

File File = new File("data2.txt");
    Scanner readUpdate = new Scanner(File);
    Player[] updatePlayers = new Player[200];
    String updateSTR;
    int updateTotalCounter = 0;
    while (readUpdate.hasNext()) {

        updateSTR = readUpdate.nextLine();
        String [] updateData = updateSTR.split(",");
        if (updateData.lenght < 5) {
            // invalid line format... print any message...
        } else {
            updatePlayers[updateTotalCounter] = new Player(updateData[0], updateData[1],updateData[2], 
                Integer.parseInt(updateData[3]), Integer.parseInt(updateData[4]));

            updateTotalCounter++;
        }

    }

    readUpdate.close();

关于java - 有关 ArrayIndexOutOfBoundsException 的问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36734372/

相关文章:

java - 根据 If 语句更改 JOptionPane 背景颜色

java - AMQP 防止自动消息读取

java - 复合主键,使用 REST 识别该资源的最佳方法是什么?

Python numpy 数组运算

java - jtable getvalue 方法不起作用

c++ - 在什么情况下 C++ 会在编译时进行数组边界检查?

java - 如何只获取窗口的可见部分(Windows、gdi32、user32 等)

读取管道分隔文件时导致问题的 Java Null 值

c - 从文件中精确打印和扫描 (C)

android - RecyclerView java.lang.IndexOutOfBoundsException : Inconsistency detected. 无效的 View 持有者适配器位置。由于更改 getItemCount()