Java-将数据从txt文件传输到数组

我目前正在尝试使用学生ID和GPA(从txt文件中获取)并使用它们来做许多其他事情的程序,例如根据GPA范围将学生分为8个类别中的1个,进行直方图每个组中的学生数,并按GPA对学生进行排名。但是,我要做的第一件事是将学生证和GPA转移到两个单独的数组中。

我知道创建数组的语法如下:

elementType[] arrayRefVar = new elementType[arraySize]

但是,我仍然不知道如何将从文件中读取的数据传递到两个单独的数组中。我必须从txt文件读取数据的代码如下:

public static void main(String[] args) throws Exception  // files requires exception handling
{
    String snum;     
    double gpa;
    Scanner gpadata = new Scanner(new File("studentdata.txt"));

    while (gpadata.hasnext()) // loop until you reach the end of the file 
    {
        snum = gpadata.next(); // reads the student's id number
        gpa = gpadata.nextDouble(); // read the student's gpa

        System.out.println(snum + "\t" + gpa); // display the line from the file in the Output window

    }
}

所以我的问题是:如何将这些信息传递到两个单独的数组中?如果我的问题难以理解,我深表歉意。我对编程非常陌生。我已经为此程序困扰了很长时间了,任何帮助将不胜感激!谢谢。

bm1128 回答:Java-将数据从txt文件传输到数组

您可以在while循环之前创建两个数组,然后将循环内的每个元素添加到每个数组。但是这种方法存在一个问题:我们不知道值的数量,因此无法为此创建一个固定大小的数组。我建议改用ArrayList,它可以根据需要增长。像这样:

public static void main(String[] args) throws FileNotFoundException {

    Scanner gpadata = new Scanner(new File("studentdata.txt"));
    List<String> IDs = new ArrayList<>();
    List<Double> GPAs = new ArrayList<>();
    while (gpadata.hasNext()) // loop until you reach the end of the file
    {
        String snum = gpadata.next(); // reads the student's id number
        double gpa = gpadata.nextDouble(); // read the student's gpa

        IDs.add(snum);
        GPAs.add(gpa);

        System.out.println(snum + "\t" + gpa); // display the line from the file in the Output window
    }
    // Use IDs and GPAs Lists for other calculations
}

使用Map将GPA与学生ID“配对”的更好方法。

编辑:

在您确定最大记录数永远不会超过1000之后,我修改了解决方案以使用数组而不是列表。我没有更改变量名称,因此您可以轻松比较解决方案。

public static void main(String[] args) throws FileNotFoundException {

    Scanner gpadata = new Scanner(new File("studentdata.txt"));
    String[] IDs = new String[1000];
    double[] GPAs = new double[1000];
    int counter = 0;

    while (gpadata.hasNext()) // loop until you reach the end of the file
    {
        String snum = gpadata.next(); // reads the student's id number
        double gpa = gpadata.nextDouble(); // read the student's gpa

        IDs[counter] = snum;
        GPAs[counter] = gpa;

        System.out.println(snum + "\t" + gpa); // display the line from the file in the Output window
        counter++;
    }
    // Use IDs and GPAs Lists for other calculations
}

请注意,我们需要一个counter(也称为索引)变量来寻址阵列插槽。

本文链接:https://www.f2er.com/3169939.html

大家都在问