作者:红杏出墙的爱_408 | 来源:互联网 | 2022-12-03 12:31
第一次发布在这里,但我有一个问题,关于一个方法没有改变它给出的数组中的值.
我认为数组是通过引用传递的,因此更改方法中的数组会在数组中更改它.然而,这对我不起作用,我不知道为什么.
我的代码如下.不起作用的方法是readFile()
package StudentsGrades;
import java.io.*;
import java.lang.*;
public class StudentsGrades {
public static void main(String [] args ) {
int numberOfLines = 0;
String fileName = "";
fileName = "marks_file.csv";
//Obtain the number of lines in the given csv.
numberOfLines = getNumberLines(fileName);
System.out.println(numberOfLines);
//initialise the arrays that the data will be stored in.
double[] gradesArray = new double[numberOfLines];
String[] studentsArray = new String[numberOfLines];
if (numberOfLines > 0) {
readFile(studentsArray, gradesArray, numberOfLines, fileName);
}
System.out.println(studentsArray[4]);
}
public static int getNumberLines (String importFile) {
int numLines = 0;
try {
FileReader fnol = new FileReader(importFile);
LineNumberReader lnr = new LineNumberReader(fnol);
while (lnr.readLine() != null ) {
numLines++;
}
} catch (FileNotFoundException fe) {
System.out.println("The file cannot be found");
} catch (Exception e) {
System.out.println("Invalid");
}
return numLines;
}
public static void readFile (String [] studentsArray, double[] gradesArray, int numLines, String fileName ) {
try {
String lineData = null;
FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
String currentLine = "";
while ((currentLine = br.readLine()) != null ) {
//Store the current Line in a string
String[] lineDataArray = currentLine.split("\\s*,\\s*");
//To index its position in the array
int index = 0;
//System.out.println(lineDataArray[1]);
studentsArray[index] = lineDataArray[0];
gradesArray[index] = Double.parseDouble(lineDataArray[1]);
System.out.println("Student: " + studentsArray[index]
+ " Grade: " + gradesArray[index]);
index++;
}
} catch (Exception e) {
System.out.println("Unexpected value in file.");
}
}
}
输出
学生:Christopher Lee年级:54.0学生:Stanley Wright年级:90.5学生:Oliver Stewart年级:75.8学生:Jessica Chang年级:34.65学生:Adam Bweon年级:66.6学生:Chrissy Yeo等级:88.9 null
正如您所看到的那样,最后一个值就是null
当我尝试从数组中打印一个值时Main
.
1> Kristjan Kic..:
将int index=0;
外循环.
如果要填充数组,则需要index
在循环之前声明.从现在开始它就在循环内部,每次都重新声明它并初始化为0.因此,当你使用它时,index总是为0,并且你会覆盖这些值.