-2

I am running the following code and I keep getting the following error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 130 out of bounds for length 130 at Datachange.init(Datachange.java:55) at Datachange.main(Datachange.java:38)

I am trying to read a file and manipulated into an output and its seems that its not reading the file well. '

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;
    }
}
user207421
  • 305,947
  • 44
  • 307
  • 483
  • This is not a 'compile issue', and it has nothing to do with either [tag:compiler-errors] or [tag:compilation]. Be clear, and don't tag indiscriminately. It is a runtime exception, and it is caused by overrunning your array beyond 130 elements. – user207421 Nov 09 '20 at 05:35
  • looks like you are reaching the end of the `variableinput` array before you reach `if(c==10)` – ColdSpike Nov 09 '20 at 05:46
  • I would replace your `variableInput` array with a `StringBuilder` object. - It's generally true that whenever you have to choose some arbitrary size to put in your code, you're doing something wrong. – CryptoFool Nov 09 '20 at 05:56
  • @makrandpawar Or end of stream. – user207421 Nov 09 '20 at 06:28

1 Answers1

0

Welcome to SO. If its ArrayIndexOutOfBound then its not compile time issue, its runtime. I'm not sure but it seems issue can be in below code block

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

Why I think there can be issue, is because in that while block you are incrementing pointer of variableinput without checking if pointer index is less than 130 or not, so if at anytime input has more characters than 130, then your code will fail as array has fixed size.

Solution to that can be to use List<Character> instead of char[]

Let me know if this not working for you.

Good luck!

semicolon
  • 487
  • 2
  • 7
  • 1
    I agree with your diagnosis. I wouldn't, however, suggest using a List to store character data. A List will be very inefficient. I would suggest using some kind of a resizable array container. A StringBuilder is an obvious choice here, – CryptoFool Nov 09 '20 at 05:54
  • Thanks guys, I tried using the list storage and it didn't work either. The thing about it is that I am trying to input/output a file in the most efficient way possible. – Kj Analytica Nov 09 '20 at 06:04
  • 1
    @KjAnalytica Well you've already failed at that by reading one character at a time from a `FileReader` directly, rather than wrapping it in a `BufferedReader`. File I/O is rarely the rate-deteminig step. You can read millions of lines per second wirh `BufferedReader.readLine()`. I suggest that is sufficient. – user207421 Nov 09 '20 at 06:28
  • Agreed @MarquisofLorne – semicolon Nov 09 '20 at 15:19
  • Agreed @Steve, we can read file in much more efficient way, including but not limited to by using Streams to read whole file and store it to list. – semicolon Nov 09 '20 at 15:23