[英]How to read a excel CSV file (comma separated value) in Java Eclipse?
目標:創建一個面向對象的圖形Java應用程序,該程序將執行以下操作:讀取CSV(逗號分隔值)文件,該文件由學生姓名(名字,姓氏),ID和內容和交付的初始標記(對於-1使用-1值)組成未評估的學生。
這是我的代碼,但是當我單擊“選擇文件”時。當它確實應該打開文件並讀取數據時,它顯示“ Expected firstName,lastName,ID,Content and Delivery”。 但由於某種原因,它無法正常工作。 在此處輸入圖片說明
下面是我的代碼:
私有類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;
導入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);
}
}
問題是您檢查了MAX_COMMAS
,但是您正在根據字段數來檢查它。 對於格式正確的文件,此值將始終為5。 因此,您可以確保到達代碼的其他部分並始終拋出。
您想要表達的是:
if (studentData.length != MAX_COMMAS)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.