目标:创建面向对象的图形Java应用程序,该程序将:读取由学生姓名(名字,姓氏),ID和初始标记组成的CSV(逗号分隔值)文件内容和交付(对未评估的学生使用-1值。
这是我的代码,但是当我点击选择文件时...它显示“预期firstName,lastName,ID,内容和交付”,它真的应该打开文件并读取数据。但不知何故它不起作用。 在此处输入图像描述
以下是我的代码:
私有类ChooseFileListener实现ActionListener {
public void actionPerformed(ActionEvent event) {
Section<Student> section;
JFileChooser fileChooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"CSV file", "csv");
fileChooser.setFileFilter(filter);
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
if (selectedFile != null) {
section = createNewSection(selectedFile);
loadStudents(section, selectedFile);
System.out.print(selectedFile);
}
}
}
}
public void RandomStudent(){
ArrayList<Student> students = new ArrayList<>();
max = (students.size()-1);
int x = (int) Math.random()* students.size();
System.out.println(x);
}
private Section<Student> createNewSection(File selectedFile) {
String filename = selectedFile.getName();
Section<Student> section = new Section<Student>(filename);
return section;
}
private void loadStudents(Section<Student> section, File selectedFile) {
Scanner in;
int MAX_COMMAS = 5;
try {
in = new Scanner(selectedFile);
String line = "";
String[] studentData;
in.nextLine();
while (in.hasNext()) {
line = in.nextLine();
studentData = line.split(",");
if (studentData.length == MAX_COMMAS) {
section.addStudent(new Student(studentData[0],studentData[1],
Integer.valueOf(studentData[2]),
Integer.valueOf(studentData[3]),
Integer.valueOf(studentData[4])));
} else {
throw new Exception(
"Invalid file format. \nExcepted: firstname, lastname, id, content, delivery");
}
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
}
我现在已经创建了另一个名为Section的部分:
包裹patel.Jainam;import java.util.ArrayList;
公共课科{
private String data;
private String FirstName;
private String LastName;
private int studentID;
private int ContentMark;
private int DeliveryMark;
private ArrayList<Student> students = new ArrayList<>();
public void FileData(String First, String Last, int ID, int Content, int Delivery){
this.FirstName = First;
this.LastName = Last;
this.studentID = ID;
this.ContentMark = Content;
this.DeliveryMark = Delivery;
}
public String setFirst(String First){
return First;
}
public String setLast (String Last){
return Last;
}
public int setstudentID (int ID) {
return ID;
}
public int setContentMark (int Content) {
return Content;
}
public int setDeliveryMark (int Delivery) {
return Delivery;
}
public Section(String data) {
this.data = data;
}
public void addStudent(Student student) {
students.add(student);
}
}
答案 0 :(得分:0)
问题是您检查MAX_COMMAS
,但是您正在根据字段数进行检查。对于格式正确的文件,此值始终为5。因此,您要确保转到代码的else部分并始终抛出。
你想要表达的是:
if (studentData.length != MAX_COMMAS)