java - 从文件创建对象的数组列表
问题描述
我有两节课Student
和Students
如何在不使用变量保存下一行并将其转换为所需数据类型(即转换为)的情况下将文件读入student
数组列表以创建对象。student
String
int
public class Student
{
private String name;
private int age;
private double gpa;
public Student(String person, int years, double avg)
{
// initialise instance variables
name = person;
age = years;
gpa = avg;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public double getGPA()
{
return gpa;
}
public class Students
{
private ArrayList<Student>students;
public Students()
{
// initialise instance variables
students = new ArrayList<Student>();
}
public void add(Student s)
{
students.add(s);
}
public Student readFile() throws IOException
{
// reads data file into ArrayList
String line;
Scanner sc = new Scanner(new File("Students.txt"));
while (sc.hasNextLine()) {
**//code to read file into student array list**
}
sc.close();
}
我试图从中读取的文件
Name0
22
1.2
Name1
22
2.71
Name2
19
3.51
Name3
18
3.91
请不要标记为重复或类似的问题。我已经广泛搜索了类似于我想要实现的已回答的问题,但没有找到任何对我有用的问题。
解决方案
要从文件中获取字符串,您可以调用 Scanner.nextString():因为您的扫描仪对象称为 sc,所以它看起来像 sc.nextString()。要获取 int,可以调用 Scanner.nextInt(),要获取 double,可以调用 Scanner.nextDouble()。
您不想将这些存储在中间值中,而是想立即创建一个学生值。您可以在 Student 构造函数中放入任何您想要的内容,只要您放入的第一件事的计算结果为 String,第二个计算结果为 int,第三个计算结果为 double。由于您的文件总是有一个 String 然后是一个 int 然后是一个 double,我认为您可以使用我上面列出的方法,并调用 Student 构造函数来获取一个 Student 值。
推荐阅读
- gitlab - 无法使用 LDAP 在 HTTPS 中克隆,错误 500
- python - OpenCV 图像校正以填充图像中的空白和孔洞
- node.js - 无法使用对话流实现将数据添加到 Firestore
- python - 如何将字符串值分配给numpy数组中的特定行和列?
- django - 解决 Docker 中的 pipenv install weasyprint 错误
- azure-ad-b2c - Azure ADB2C 中的电话注册和登录自定义策略不起作用
- python - 静态 css 文件未在 Django 管理员中加载
- javascript - Firebase 实时数据库:如何获取父节点的值
- kdb - 在 kdb+ 中选择和索引访问表的翻转结果不同
- android - 为 WebView 添加窗口事件监听器并调用 Java 函数