簡體   English   中英

Java-如何創建要在txt文件下讀取的每一行的對象

[英]Java - How to create an object of each line being read in under a txt file

我有下面的方法,它使用hasNext讀取txt文件的每一行,因此可以工作,但是誰能告訴我我將如何創建要讀取的每一行的對象。

謝謝

private static Queue readFile(Scanner input) {
            Queue newQueue = new Queue ();
            while(input.hasNext()) {
                try {
                    String txtLine = input.nextLine();
                    System.out.println(txtLine);
                } catch(Exception e) {
                    System.out.println("ERROR");  
                }       

            }
               return newQueue;
       }

你已經做了。 字符串txtLine = input.nextLine(); 創建一個名為txtLine的String對象。 如果您嘗試將其添加到隊列中,則也需要這樣做。 現在,您的代碼只會將它們全部打印出來,而不會將它們放入隊列。

也許:

ArrayList<Queue> array = new ArrayList<Queue>();
        Queue newQueue = new Queue ();
        while(input.hasNext()) {
            try {
                String txtLine = input.nextLine();
                newQueue.setLine(txtLine);
                array.add(newQueue);
                System.out.println(txtLine);
            } catch(Exception e) {
                System.out.println("ERROR");  
            }     
        }
           return array;

暫無
暫無

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

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