我正在尝试创建一个读取CSV文件的程序,然后将读取的值放入2D双数组中。
名为DataMatrix的类包含2D数组作为私有实例变量(至少我相信如此)。 现在我想找到这个数组的行平均值但是我注意到的是,当我调用计算平均值的方法时,数组被重置为它的默认值。 我确定这是初学者的错误,但感谢您提前获得任何帮助。
这是DataMatrix类:
public class DataMatrix{
private String rawInput;
private double[][] finalArr;
private String[] rows;
private String[][] arr;
public DataMatrix(){
rawInput = "";
rows = new String [1];
arr = new String [1][1];
finalArr = new double[arr.length][arr[0].length];
}
public void setInput(String input){
rawInput = input;
}
public void setDoubleArray(){
rows = rawInput.split("\n");
arr = new String [rows.length][];
//Temporarly hold the values in the enhanced for loop, and re-split into the 2D array
int counter = 0;
for(String rowData: rows){
arr[counter] = rowData.split(",");
counter++;
}
//Convert the string to a double
double[][] finalArr = new double[arr.length][arr[0].length];
for (int i = 0; i < arr[0].length; i++){
finalArr[0][i] = Double.valueOf(arr[0][i]);
}
for (int i = 0; i < arr.length; i++){
finalArr[i][0] = Double.valueOf(arr[i][0]);
}
//Debug
System.out.println(finalArr[0][0]+ " Size: "+ finalArr.length);
}
public double calcRowAvg(){
//Debug
System.out.println(finalArr[0][0] + " Size: "+ finalArr.length);
return 0;
}
以下是主要课程:
public class DataRun{
public static void main(String[] args){
//Make sure the user passed the command line argument
if (args.length != 1){
System.out.println("Assignment1 takes exactly one command-line argument.");
System.out.println("Usage: java Assignment1 some_file.csv");
System.exit(0);
}
//Set filename to arguement
String csvFileName = args[0];
//Instantiate file reader
CSVReader fileReader = new CSVReader();
//Read the file into a string
String text = fileReader.readFile(csvFileName);
//Start array processing
DataMatrix CSVCalc = new DataMatrix();
CSVCalc.setInput(text);
CSVCalc.setDoubleArray();
double rowAvg = CSVCalc.calcRowAvg();
double colAvg = CSVCalc.calcColAvg();
System.out.println("Row: " + rowAvg + " Col: " + colAvg);
}
抱歉这个巨大的糊状物。