首页 > 解决方案 > 如何从循环中访问所有输入,以便将其存储为对象?

问题描述

我正在读取一个小文件(使用 Java 扫描器),将这些行解析为特定的字符串,并将字符串中的信息存储到一个对象中。我只能访问最后一个元素,但是当我移动我的新对象声明并尝试从循环内部添加一些东西时,它会弄乱我的代码,我什么也得不到。我需要通过几个不同的循环来获取所有信息,但我只得到最后一个。我们应该只扫描一次,我想。

我添加了一个计数,认为我可以添加另一个循环(之后),但它甚至会访问相同的信息吗?

但是如何获取所有对象,以便将它们添加到我的 arrayList 中?

public static void main(String[] args) throws FileNotFoundException {
         // read in the song file and build the songs array
        File text = new File ("short.txt");
        Scanner scnr = new Scanner (text);
        
        String artist = " ";
        String title = " ";
        String lyrics = " ";
        
        int count =0; 
        ArrayList <Song> song_list = new ArrayList<Song>();
        
        
        while (scnr.hasNextLine()){
            String next = scnr.nextLine();
            
            
            if (next.startsWith("ARTIST")){
                artist = (next.substring(8, next.length()-1));
                
            }
            else if (next.startsWith("TITLE")) {
                title = (next.substring(7, next.length()-1));
                count++;
            }
            else if (next.startsWith("LYRICS")) {
                lyrics = (next.substring(8, next.length())+"\n");
            }
                if (!next.contains("\"")){
                    StringBuilder sb = new StringBuilder();
                    lyrics += sb.append(next) + "\n";
                }
            }
        
        Song songs = new Song (artist, title, lyrics);
        song_list.add(songs);
        System.out.print(songs);
        
        
        scnr.close();

感谢您的任何帮助!

标签: javaloopsobjectarraylistjava-11

解决方案


如果文件总是有序的,你可以改变你的代码来测试如果lyrics不是空的,然后插入到你的列表中

while (...) {
   // read artists
   // read title
   // read lyrics

   if (!lyrics.isEmpty()) {
       // create song and add to list
       // then reset lyrics to empty
   }
}

推荐阅读