我正在尝试制作一个对 2D 数组执行某种排序的程序,但我无法找到一种方法将 CSV 文件中的数据放入 2D 数组中。我知道数组列表,但我不想在这里使用数组列表。
如果除了有关数组的事情之外不对程序的其他部分进行任何更改,我将不胜感激
我现在可以正确编译代码,但是当程序运行时,我得到 ArrayIndexOutOfBoundsException:索引 5 超出长度 5 的范围
数据存储在 CSV 文件中:
Lana,20,6.3
Daniel,30,2.8
Lucas,29,4.9
Henry,19,8.2
Johnny,59,5.3
代码:
import java.util.*;
import java.io.*;
public class personProgram
{
public static void main(String[] args)
{
readFile("PersonStorage.csv");
}
public static void readFile(String pFileName)
{
FileInputStream fileStream = null;
InputStreamReader rdr;
BufferedReader bufRdr;
int lineNum;
String line;
try
{
fileStream = new FileInputStream(pFileName);
rdr = new InputStreamReader(fileStream);
bufRdr = new BufferedReader(rdr);
lineNum = 0;
line = bufRdr.readLine();
while(line != null)
{
lineNum++;
processLine(line);
line = bufRdr.readLine();
}
fileStream.close();
}
catch (IOException errorDetails)
{
if(fileStream != null)
{
try
{
fileStream.close();
}
catch(IOException ex2)
{ }
}
System.out.println("Error in fileProcessing: " + errorDetails.getMessage());
}
}
private static void processLine(String csvRow)
{
String[] data;
data = csvRow.split(",");
int lineLength = data.length;
String name = data[0];
int age = Integer.parseInt(data[1]);
double time = Double.parseDouble(data[2]);
int rows = 5;
int cols = 3;
Person[][] persons = new Person[rows][cols];
persons[rows][0] = new Person(name, age, time);
rows++;
//this is me testing
System.out.print(persons[2][0]);
}
}
检查代码,如果你想要的话
import java.io.File;
import java.nio.file.Files;
import java.util.List;
public class PersonProgram {
public static void main(String[] args) {
readFile("./PersonStorage.csv");
}
public static void readFile(String pFileName) {
File file = new File(pFileName);
if (!file.exists()) {
System.err.println("File does not exist: " + pFileName);
return;
}
try {
List<String> lines = Files.readAllLines(file.toPath());
Person[] persons = new Person[lines.size()];
int index = 0;
for (String line : lines) {
processLine(line, persons, index++);
}
System.out.println("Processed " + persons.length + " persons");
} catch (Exception e) {
System.err.println("Failed to read file: " + pFileName);
}
}
private static void processLine(String csvRow, Person[] persons, int index) {
if (csvRow == null || csvRow.isEmpty()) {
return;
}
String[] data = csvRow.split(",");
String name = data[0];
int age = Integer.parseInt(data[1]);
double time = Double.parseDouble(data[2]);
persons[index] = new Person(name, age, time);
//this is me testing
System.out.println(persons[index]);
}
}