【发布时间】: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-errors 或compilation 无关。要清楚,不要乱加标签。这是一个运行时异常,它是由超出 130 个元素的数组引起的。
-
看起来您在到达
if(c==10)之前到达了variableinput数组的末尾 -
我会用
StringBuilder对象替换您的variableInput数组。 - 通常情况下,当您必须选择任意大小来放入代码时,您就做错了。 -
@makrandpawar 或流结束。
标签: java indexoutofboundsexception