【问题标题】:Method not changing array in main方法不改变主数组
【发布时间】:2019-03-07 11:08:00
【问题描述】:

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

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

我的代码如下。无效的方法是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 学生:斯坦利赖特等级:90.5 学生:奥利弗·斯图尔特等级:75.8 学生:Jessica Chang 成绩:34.65 学生:Adam Bweon 成绩:66.6 学生:Chrissy Yeo 成绩:88.9 空

如您所见,最后一个值是null,那是我尝试从Main 内的数组中打印一个值。

【问题讨论】:

  • 顺便说一句:你应该关闭所有这些读者!

标签: java arrays loops methods


【解决方案1】:

int index=0; 放在循环之外。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-13
    • 1970-01-01
    • 2019-12-04
    • 1970-01-01
    • 2018-10-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多