繁体   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