gpt4 book ai didi

java - 文本文件操作: Take data from text file and write a new text file with the data taken from the original file

转载 作者:太空宇宙 更新时间:2023-11-04 09:58:46 25 4
gpt4 key购买 nike

我正在编写一个程序来操作文本文件中的一些数据。我应该从包含比这 4 个信息更多的信息的文件中获取州 ID、人口、入学率和贫困率,并将它们写入一个新的文本文件。然后使用这个新的文本文件做一些数学运算。这是原始文本文件结构:
This is the original text file structure我在代码中遇到了错误,希望得到一些帮助。具体来说,错误是索引越界,并且无法从此上下文引用非静态方法。

定义要提取的数据的类:
Class to define data for extraction完成实际提取的类:
Class where the actual extraction is done 公共(public)人口数据(字符串stateId,字符串totPopulation,字符串 schoolGoingPopuplation, 字符串 povertPopulation) { this.stateId = stateId; this.totPopulation = totPopulation; this.schoolGoingPopuplation = schoolGoingPopuplation; this.povertPopulation = povertPopulation; }

  public String getState()
{
return stateId;
}

public String getPopulation()
{
return totPopulation;
}

public String getSchool()
{
return schoolGoingPopuplation;
}

public String getPoverty()
{
return povertPopulation;
}

public String toString()
{
return this.stateId + " " + this.totPopulation + " " +
this.schoolGoingPopuplation + " " + this.povertPopulation;
}

//这是主类

         inFile = new InputStreamReader(new FileInputStream(inFileName));

OutputStreamWriter outFile = new OutputStreamWriter(new FileOutputStream(outFileName));

while(scanner.hasNext()) {

String line = scanner.nextLine();

String[] columns = line.split(" ");

String sateId = columns[0];

String totPopulation = columns[9];

String schoolGoingPopuplation = columns[10]; //index out of bounds occured

String povertPopulation = columns[11]; //index out of bounds occured

PopulationData pd = new PopulationData(sateId, totPopulation, schoolGoingPopuplation, povertPopulation);
data.add(pd);

outFile.write(pd.toString());
}
for(PopulationData pd : data){
System.out.println(pd.toString());
}
}
catch(IOException except)
{
except.printStackTrace();
}
}

最佳答案

第 28,30,32 行:文件中的字段是否真的由制表符分隔,并且恰好是一个制表符?看起来不像。我的猜测是它使用了空格,并且您的拆分生成了一个仅包含一列的数组,即整行。鉴于您有一个扫描仪实例,您可能打算使用它来通过 .nextInt().next() 方法读取字段。

第 37 行:.add() 方法返回一个 boolean 值,您正尝试将其写入流。您可能想写 outfile.write(pd.toString())

第 40 行:您可能指的是 System.out.println(pd.toString()),您所拥有的实际上是 PopulationDataManipulation.toString(),它不起作用,因为它是一个实例方法,而您的 main 是静态的。

关于java - 文本文件操作: Take data from text file and write a new text file with the data taken from the original file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53769728/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com