gpt4 book ai didi

java - 我将如何使用缓冲读取器将 .txt 文件转换为 ArrayList 以及如何操作该对象?

转载 作者:行者123 更新时间:2023-12-01 13:50:05 25 4
gpt4 key购买 nike

我的项目首先从文本文件导入数据并将其转换为 ArrayList。我对 ArrayList 不太熟悉,也不知道它是如何工作的。我已经提供了讲师提供的入门文件,看起来我需要使用缓冲阅读器来导入文本文件。因为本类(class)习惯于提供起始代码,但没有很好地解释该代码的作用,所以我也希望能简单地解释一下什么是 bufferedreader,以及如果我也有的话,我将如何自己创建一个。这是打开时显示的文本文件:

manny 89 78 100 91 67
cindy 66 81 94 80 71
timmy 85 59 100 83 21
mikey 88 76 69 82 90
kelly 68 93 63 92 55
sandy 80 73 67 51 99

这是起始代码:

    import java.util.*;
import java.io.*;

public class ExamScores
{
public static void main( String args[] ) throws Exception
{
// close/reuse this file handle on the next file
BufferedReader infile = new BufferedReader( new FileReader( "ExamScores.txt" ) );

// you declare all needed ArrayLists and other variables from here on.

System.out.println("\nSTEP #1: 50%"); // 50%

System.out.println("\nSTEP #2: 25%"); // 75 %

System.out.println("\nSTEP #3: 10%"); // 85%

System.out.println("\nSTEP #4: 15%"); // 100%

} // END MAIN

// - - - - - - H E L P E R M E T H O D S H E R E - - - - -


} // END EXAMSCORES CLASS

创建 ArrayList 后,我​​该如何操作它来执行诸如按字母顺序对名称进行排序之类的操作。 ArrayList 是否很像二维数组,或者该文本文件中的每一行都是一个单独的数组列表?为了了解我在这个项目中需要做的一切,我必须在数组列表中按字母顺序对名称进行排序。然后我需要计算每个名字的平均分,最后我需要计算每个学生第一次、第三次和第五次考试的平均分,并找出他们在这三次考试中哪一次的平均分最低?我并不是为了迎合该项目的确切答案,但我想提供目前我预计能够使用数组列表执行的操作的所有信息。谢谢。

最佳答案

您可以使用java.io.BufferedReader用字符串填充 ArrayList

    BufferedReader inFile = new BufferedReader(new FileReader("ExamScores.txt"));

//Define and initialise the ArrayList
ArrayList<String> examScores = new ArrayList<String>(); //The ArrayList stores strings

String inLine; //Buffer to store the current line
while ((inLine = inFile.readLine()) != null) //Read line-by-line, until end of file
{
examScores.add(inline);
}
inFile.close(); //We've finished reading the file
<小时/>

访问 java.util.ArrayList 中的元素

    //Loop through all elements in the list and output their values
for (int i=0; i < examScores.size(); i++)
System.out.println(examScores.get(i));
<小时/>

对 ArrayList 进行排序更加困难。对于您的程序,最好解析字符串并将值存储到自定义 StudentExams 类中。这是我为您制作的原型(prototype)示例

    public class StudentExams
{
private String studentName;
private int examScores[];

//Inline is the String we get from inFile.readLine();
public StudentExams(String inline)
{
//Pesudo-code
parse the string using String.split(" ");
store parsed values into studentName and examScores;
}

public String getStudentName()
{
return studentName;
}

public int[] getExamScores()
{
return examScores;
}
}

String#split(String regex) 的文档

教程:How to use String#split(String regex)

<小时/>

我没有给你直接的答案,但我已经给你足够的信息来让你自己拼凑出答案。您可以阅读上述主题的所有教程。互联网上有很多示例可以完全满足您的要求,您只需尝试一下即可。

关于java - 我将如何使用缓冲读取器将 .txt 文件转换为 ArrayList 以及如何操作该对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20034137/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com