所以,我有一个类创建一个包含标题的歌曲对象:艺术家:专辑。我提示用户询问特定的艺术家,然后从包含主播放列表的 ArrayList 中,程序为每个特定的艺术家返回一个按标题排序的列表。这没问题。我遇到的问题是用户要求的艺术家不在主播放列表中。当我使用 if/then/else 对此进行编码时,对于提示的艺术家与主播放列表中的艺术家不匹配的每种情况,我都会收到一个 Sysout。此外,当用户输入正确的艺术家时,会生成正确的、格式化的 Arraylist,以及与提示名称不匹配的每个艺术家的 Sysout(因此,本质上是整个主列表)。我需要返回一个格式化的 ArrayList 只包含提示的艺术家,或单个声明,例如“未在列表中找到艺术家”。我已经被困了几个小时,如果你愿意的话,我需要一些新的想法。我知道为什么会这样,我只是想不出我想要的输出。此外,在理解为什么 ignoreCase() 对我不起作用(用于检查 searchArtist 与 Song 对象的实例变量)的一些帮助将有很大帮助。
以下是当前代码:
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.*;
public class SongList {
public static void main(String[] args){
//An arraylist theList to accept a file containg title : artist : album
ArrayList<Song> theList = new ArrayList<Song>();
try{
Scanner in = new Scanner(System.in);
File inputFile;
// Prompts user for proper input
do{ System.out.println("Please enter a valid input file.");
String input = in.next();
inputFile = new File(input);
}while(!inputFile.exists());
Scanner inp = new Scanner(new FileReader(inputFile));
String line = "";
//Accepts a line that is greater in length that 2 (it assumes a colon, and one blank space)
while((inp.hasNextLine()))
{
line = inp.nextLine();
line = line.trim();
if(line.length() > 2){
Song n = createSong(line);
theList.add(n);
}
}
}
catch(Exception e){
System.out.println("Error with the input file: " + e.getMessage());
}
Collections.sort(theList); //Sorts by title
//An arrayList particularArtist that creates an arrayList of a specified artist as given by the user
ArrayList<Song> particularArtist = new ArrayList<Song>();
Scanner sa = new Scanner(System.in);
String searchArtist = "";
System.out.print("Please enter the name of an artist you'd like to find.");
searchArtist = sa.next();
//This is where I am having the issue.
for(Song theArtist : theList)
if(theArtist.getArtist().contains(searchArtist))
{
particularArtist.add(theArtist);
}
else{System.out.println("The artist you are looking for does not exist in the play list.");}
for(Song is : particularArtist)
System.out.println(is);
}
/*
* Method for creating a Song object given an input file. In the format "Title : Artist: Album," substrings
* are created at the colons, and white space is trimmed.
*/
public static Song createSong(String a) {
int index1 = a.indexOf(':');
int index2 = a.indexOf(':', index1 + 1);
Song s = new Song(a.substring(0, index1).trim(), a.substring(index1 + 1, index2).trim(), a.substring(index2 + 1).trim());
return s;
}
}