【发布时间】:2023-04-08 16:55:02
【问题描述】:
我是新手(进入 java 6 周)试图从 csv 文件中删除元素,该文件列出了一组学生,例如(id, name, grades),每个都在一个新行上。
每个学生id 都按升序编号。我想尝试通过输入身份证号码来删除学生,但我不知道该怎么做。
到目前为止,我只是尝试减少用户输入的值以匹配索引,因为学生按数字列出,我在 while 循环中执行了此操作。但是,每次迭代都无法识别先前用户输入的减少,我认为我需要一种可以仅搜索 id 值并从 csv 文件中删除整行的方法。
仅尝试包含相关代码。阅读以前的堆栈问题向我展示了一堆与节点相关的答案,这对我来说毫无意义,因为我没有理解它所需的任何先决知识,而且我不确定我的其余代码是否适用那些方法。
有什么比较简单的想法吗?
Student.txt(各换行)
1,Frank,West,98,95,87,78,77,80
2,Dianne,Greene,78,94,88,87,95,92
3,Doug,Lei,78,94,88,87,95,92
etc....
代码:
public static boolean readFile(String filename) {
File file = new File("C:\\Users\\me\\eclipse-workspace\\studentdata.txt");
try {
Scanner scanner = new Scanner(file);
while(scanner.hasNextLine()) {
String[] words=scanner.nextLine().split(",");
int id = Integer.parseInt(words[0]);
String firstName = words[1];
String lastName = words[2];
int mathMark1 = Integer.parseInt(words[3]);
int mathMark2 = Integer.parseInt(words[4]);
int mathMark3 = Integer.parseInt(words[5]);
int englishMark1 = Integer.parseInt(words[6]);
int englishMark2 = Integer.parseInt(words[7]);
int englishMark3 = Integer.parseInt(words[8]);
addStudent(id,firstName,lastName,mathMark1,mathMark2,mathMark3,englishMark1,englishMark2,englishMark3);
}scanner.close();
}catch (FileNotFoundException e) {
System.out.println("Failed to readfile.");
private static void removeStudent() {
String answer = "Yes";
while(answer.equals("Yes") || answer.equals("yes")) {
System.out.println("Do you wish to delete a student?");
answer = scanner.next();
if (answer.equals("Yes") || answer.equals("yes")) {
System.out.println("Please enter the ID of the student to be removed.");
//tried various things here: taking userInput and passing through linkedlist.remove() but has never worked.
【问题讨论】:
-
提供studentdata.txt示例文件,包含少量记录。
-
1,Frank,West,98,95,87,78,77,80 2,Dianne,Greene,78,94,88,87,95,92 3,Doug,Lei,78, 94,88,87,95,92
-
您是否尝试过使用任何 Java 库(如 CSVReader 或 Apache Commons CSV)来实现它
标签: java linked-list