我是个新手(刚接触java 6周),试图从一个csv文件中删除元素,该文件列出了一组学生,例如(id,name,grades)
,每个都在一个新行中。
每个学生id
均按升序编号。我想尝试通过输入 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.
最佳答案
这个解决方案可能不是最优的或漂亮的,但它确实有效。它逐行读入输入文件,将每一行写入临时输出文件。每当它遇到与您要查找的内容相匹配的行时,它就会跳过将该行写出。然后它会重命名输出文件。我在示例中省略了错误处理、关闭读取器/写入器等。我还假设您要查找的行中没有前导或尾随空格。根据需要更改 trim() 周围的代码,以便找到匹配项。
File inputFile = new File("myFile.txt");
File tempFile = new File("myTempFile.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = "bbb";
String currentLine;
while((currentLine = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)) continue;
writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close();
reader.close();
boolean successful = tempFile.renameTo(inputFile);
关于java - 如何根据用户输入从java中的链表中删除特定元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59441550/