【问题标题】:How do I access all of my input from my loop so I can store it as an object?如何从循环中访问所有输入,以便将其存储为对象?
【发布时间】:2021-11-05 17:13:05
【问题描述】:

我正在读取一个小文件(使用 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();

感谢您的帮助!

【问题讨论】:

  • @ScaryWombat 它在方括号之外......你会在循环之前声明它吗?
  • 文件是否总是有序的? ARTISTS, TITLE LYRICS ?
  • @ScaryWombat 是的!单独一行中的单个双引号将歌词与下一位艺术家分隔开来。
  • 您能否在问题中包含一个示例输入文件?给出答案以及可以对代码进行的改进会容易得多。

标签: java loops object arraylist java-11


【解决方案1】:

如果文件总是有序的,您可以更改代码以测试lyrics 是否为空,然后插入到您的列表中

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

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

【讨论】:

    猜你喜欢
    • 2014-03-19
    • 1970-01-01
    • 2015-08-30
    • 2017-03-29
    • 2020-12-01
    • 1970-01-01
    • 2020-07-11
    • 2018-01-28
    • 2022-11-04
    相关资源
    最近更新 更多