【问题标题】:Java Runtime Issue: ArrayIndexOutOfBoundsException: Index 130 out of bounds for length 130 [duplicate]Java 运行时问题:ArrayIndexOutOfBoundsException:索引 130 超出长度 130 [重复]
【发布时间】:2020-11-09 05:24:26
【问题描述】:

我正在运行以下代码,但不断收到以下错误:

线程“main”java.lang.ArrayIndexOutOfBoundsException 中的异常:Datachange.init(Datachange.java:55) 处 Datachange.main(Datachange.java:38) 处的索引 130 超出长度 130 的范围

我正在尝试读取文件并操作到输出中,但它似乎没有很好地读取文件。 '

import java.io.*;

public class Datachange
{
    public class variables
    {
    private char [] body;
    private int ID;
    private int population;
    private int populationchilds;
    private int populationchildspoverty;
    private double populationchildpovertypercent;

        variables(char [] input)
        {
        body = input;

        char[] stateID = java.util.Arrays.copyOfRange(body,0,2);
        ID = Integer.parseInt(new String(stateID).trim());

        char[] totalpopulation  = java.util.Arrays.copyOfRange(body,83,90);
        population = Integer.parseInt(new String(totalpopulation).trim());

        char [] childpopulation = java.util.Arrays.copyOfRange(body,92,99);
        populationchilds = Integer.parseInt(new String(childpopulation).trim());

        char [] povertychilds = java.util.Arrays.copyOfRange(body,101,108);
        populationchildspoverty = Integer.parseInt(new String(povertychilds).trim());
        }
    }




    public static void main(String[] args)
    {
        Datachange DS = new Datachange();
        DS.init();
    }


    public void init()
    {
        variables dataframe[] = new variables[13486];

        try (FileReader inputDataframe = new FileReader("SmallAreaIncomePovertyEstData.txt"))
        {
            int c;
            int i = 0;
            int j = 0;
            char variableinput [] = new char[130];

            while((c = inputDataframe.read())!=-1)
            {

                    variableinput[i] = (char) c;
                    i++;


                if(c==10)
                {
                    dataframe[j] = new variables(variableinput);
                    j++;
                    i = 0;
                }
            }
        }
        catch(IOException except)
        {
            System.out.println("There is Input/Output Error:" + except.getMessage());
        }
        this.newdata(dataframe);
    }


    public variables[] newdata(variables[] dataset)
    {
        variables[] newdata=new variables[57];

        try (BufferedWriter outData = new BufferedWriter(new
                FileWriter("SmallAreaIncomePovertyEstDatanew.txt")))
        {
            int stateID = 1; //First ID
            int statePop= 0;
            int stateChdPop=0;
            int stateChdPovertyPop=0;

            for(int i=0;i<dataset.length;i++)
            {
                if (dataset[i].ID == stateID)
                {
                    statePop += dataset[i].population;
                    stateChdPop += dataset[i].populationchilds;
                    stateChdPovertyPop += dataset[i].populationchildspoverty;
                }

                else
                {
                    double stateChdPovertyPopPercent=0;
                    if (stateChdPop != 0)
                    {
                        stateChdPovertyPopPercent = (double)
                                stateChdPovertyPop/stateChdPop * 100;
                        int z = 12;
                    }

                    else
                    {
                        stateChdPovertyPopPercent = 0;
                    }

                    outData.append(stateID + "\t" + statePop + "\t" +
                            stateChdPop + "\t" + stateChdPovertyPop+
                            "\t" + stateChdPovertyPopPercent + "\n");

                    statePop = 0;
                    stateChdPop = 0;
                    stateChdPovertyPop = 0;
                    i--;
                    stateID++;
                }
            }
        }
        catch(IOException except)
        {
            System.out.println("I/O Error:" + except.getMessage());
        }

        int x = 12;
        return newdata;
    }
}

【问题讨论】:

  • 这不是“编译问题”,与compiler-errorscompilation 无关。要清楚,不要乱加标签。这是一个运行时异常,它是由超出 130 个元素的数组引起的。
  • 看起来您在到达 if(c==10) 之前到达了 variableinput 数组的末尾
  • 我会用 StringBuilder 对象替换您的 variableInput 数组。 - 通常情况下,当您必须选择任意大小来放入代码时,您就做错了。
  • @makrandpawar 或流结束。

标签: java indexoutofboundsexception


【解决方案1】:

欢迎来到 SO。如果它的 ArrayIndexOutOfBound 则不是编译时问题,而是它的运行时问题。我不确定,但似乎问题可能在下面的代码块中

while((c = inputDataframe.read())!=-1)

为什么我认为可能存在问题,是因为在那个 while 块中,您正在递增 variableinput 的指针而不检查指针索引是否小于 130,所以如果在任何时候输入的字符数超过 130,那么您的由于数组的大小固定,代码将失败。

解决方案是使用List&lt;Character&gt; 而不是char[]

如果这不适合你,请告诉我。

祝你好运!

【讨论】:

  • 我同意你的诊断。但是,我不建议使用 List 来存储字符数据。列表将非常低效。我建议使用某种可调整大小的数组容器。 StringBuilder 是一个明显的选择,
  • 谢谢大家,我尝试使用列表存储,但它也不起作用。关于它的事情是我正在尝试以最有效的方式输入/输出文件。
  • @KjAnalytica 好吧,您已经失败了,直接从FileReader 中一次读取一个字符,而不是将其包装在BufferedReader 中。文件 I/O 很少是决定速率的步骤。您可以通过BufferedReader.readLine() 每秒读取数百万行。我认为这就足够了。
  • 同意@MarquisofLorne
  • 同意@Steve,我们可以以更高效的方式读取文件,包括但不限于使用 Streams 读取整个文件并将其存储到列表中。
猜你喜欢
  • 2021-02-20
  • 1970-01-01
  • 1970-01-01
  • 2021-11-14
  • 1970-01-01
  • 1970-01-01
  • 2019-10-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多