簡體   English   中英

如何從txt文件讀取行並將每行添加到LinkedList類型?

[英]How do I read lines from a txt file and add each line to a type LinkedList?

因此,基本上,該程序調用以使用類類型LinkedList來存儲文本文件中的行。 當然,我是一個單獨的課程,所以這就是我正在使用的LinkedList的類型。 這是程序正在讀取的txt文件

CPSC141 Computer_Organization   3   D
CPSC130 Computer_ProgrammingI   3   B
Math140 Calculus_I  4   E
CPSC232 Assembler_Languages 3   B
CPSC131 Computer_ProgramingII 3 A
Math141 Calculus_II 4   B

這是我的代碼

File inFile = new File("courses.txt");
    Scanner f = new Scanner(inFile);
    while (f.hasNextLine())
    {
        Courses.add(f);
    }
    f.close();

問題是我收到一條錯誤消息,內容如下:

method.java.util.Collection.add(Course) is not applicable;
(argument mismatch; java.util.Scanner cannot be converted to Course);

我不知道如何將字符串從txt文件轉換為類型Course(我的單獨班級)

在Java 8中,您可以簡單地使用:

List<String> yourList = Files.readAllLines(Paths.get("courses.txt"));

fScanner實例。 將其更改為在下一行中讀取的行。

//from
Courses.add(f);
//To
Courses.add(f.nextLine());

現在,變量f是Scanner實例。 您可以使用String.valueOf或toString()方法將其轉換為字符串,也可以將整個行讀取為字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM