【发布时间】:2015-10-23 21:46:04
【问题描述】:
我编写了一个代码,它从 txt 文件中取出一行,将其拆分为不同的字符串和整数,然后将其作为一个名为professor 的对象存储到一个数组列表中。主类的代码是这样的:
public class Main {
public static void main(String[] args) throws IOException {
FileReader file = new FileReader("text.txt");
BufferedReader reader = new BufferedReader(file);
ArrayList<Profesor>professors = new ArrayList<Profesor>();
String line = reader.readLine();
String[] lineSplit = new String[11];
while(line != null){
lineSplit = line.split("\\s+");
professors.add(new Profesor(lineSplit[0], lineSplit[1], Integer.parseInt(lineSplit[2]), Integer.parseInt(lineSplit[3]), Integer.parseInt(lineSplit[4]), Integer.parseInt(lineSplit[5]), Integer.parseInt(lineSplit[6]), Integer.parseInt(lineSplit[7]), Integer.parseInt(lineSplit[8]), Integer.parseInt(lineSplit[9]), Integer.parseInt(lineSplit[10]), Integer.parseInt(lineSplit[11])));
}
}
}
Profesor 类:
public class Profesor {
private String name;
private String subject;
private int wh0;
private int wh1;
private int wh2;
private int wh3;
private int wh4;
private int wh5;
private int wh6;
private int wh7;
private int wh8;
private int wh9;
public Profesor(String n, String s, int w0, int w1, int w2, int w3, int w4, int w5, int w6, int w7, int w8, int w9){
name = n;
subject = s;
wh0 = w0;
wh1 = w1;
wh2 = w2;
wh3 = w3;
wh4 = w4;
wh5 = w5;
wh6 = w6;
wh7 = w7;
wh8 = w8;
wh9 = w9;
}
}
txt 文件类似于:
Jhon Maths 173 486 789 954 684 235 446 168 749 851
Robert MathsII 283 686 948 978 144 224 473 468 778 845
问题是如何将数组列表显示到控制台中?
以及如何访问 arraylist 内的一个对象内的字符串?
提前致谢
【问题讨论】:
-
你没听说过数组吗?!
-
数组不起作用,因为我不知道 txt 文件中的行数,您必须为数组设置大小
-
呃,我的意思是,为什么
Professor的构造函数需要 10 个整数作为输入.. -
搜索您的教授类应覆盖的
toString()方法。此外,所有这些数字都应该存储在他们自己的数组列表或教授类的数组字段中。 -
我现在明白你的意思了,哈哈,没考虑过我会编辑它,但这并不能回答我关于如何显示数组列表的问题