Java 方法不更改main中的数组

Java 方法不更改main中的数组,java,arrays,loops,methods,Java,Arrays,Loops,Methods,第一次在这里发布,但我有一个问题,关于一个不改变数组中给定值的方法 我认为数组是通过引用传递的,因此在方法中更改数组会在数组中更改它。然而,这对我不起作用,我也不知道为什么 我的代码如下。无效的方法是readFile() 输出 学生:Christopher Lee成绩:54.0 学生:斯坦利·赖特成绩:90.5 学生:奥利弗·斯图尔特成绩:75.8 学生:Jessica Chang年级:34.65 学生:Adam Bweon年级:66.6 学生:杨洁篪成绩:88.9 空的 正如您所看到的,最后一

第一次在这里发布,但我有一个问题,关于一个不改变数组中给定值的方法

我认为数组是通过引用传递的,因此在方法中更改数组会在数组中更改它。然而,这对我不起作用,我也不知道为什么

我的代码如下。无效的方法是
readFile()

输出

学生:Christopher Lee成绩:54.0 学生:斯坦利·赖特成绩:90.5 学生:奥利弗·斯图尔特成绩:75.8 学生:Jessica Chang年级:34.65 学生:Adam Bweon年级:66.6 学生:杨洁篪成绩:88.9 空的


正如您所看到的,最后一个值是
null
,这是当我尝试从
Main
中的数组中打印一个值时在循环之外

如果要填充数组,需要在循环之前声明
index
。 因为现在它在循环中,所以每次都会重新声明并初始化为0。
因此,当您使用索引时,它总是0,您会覆盖这些值。

Place
int index=0在循环之外

如果要填充数组,需要在循环之前声明
index
。 因为现在它在循环中,所以每次都会重新声明并初始化为0。
因此,当您使用索引时,它总是0,您会覆盖这些值。

btw:您应该关闭所有这些读卡器!顺便说一句:你应该关闭所有的阅读器!
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.");
    }

}
}