java - 如何从循环中访问所有输入,以便将其存储为对象?
问题描述
我正在读取一个小文件(使用 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();
感谢您的任何帮助!
解决方案
如果文件总是有序的,你可以改变你的代码来测试如果lyrics
不是空的,然后插入到你的列表中
while (...) {
// read artists
// read title
// read lyrics
if (!lyrics.isEmpty()) {
// create song and add to list
// then reset lyrics to empty
}
}
推荐阅读
- c# - 除非在单引号或双引号中,否则如何用空格分隔字符串
- julia - 矩阵上的循环移位
- php - 如何在 Wordpress 的存档页面上显示所有类别的帖子?
- authentication - 是否有一种经济高效的方式来协调多个登录流程,主要是 OAuth2?
- c# - Unity C# - Time.time & time.deltatime
- python - Keras RNN 未对所有训练数据进行训练
- javascript - 使用html表单提交未将对象添加到数组中
- r - 为什么 as_tibble(mtcars,rownames = NA) 不显示行名?文档说它应该
- laravel - 传递给 Tymon\JWTAuth\JWTGuard::login() 的参数 1 必须实现接口 Tymon\JWTAuth\Contracts\JWTSubject
- machine-learning - 如何使用神经网络对大量类进行分类?