I have the code attached below to search through an array for a specific string but this code isn't working. Why? if(children[x].equals(music)) does work but only if you type in the full file name (stored in the music variable) how can I make it so that if the value of music is 'h' any element in the children array containing the character 'h' will print as an output?
public class main {
public static void main(String[] args) throws IOException {
//text file, should be opening in default text editor
//Look through directory
File dir = new File("/Users/Runa.c/Music/music");
String[] children = dir.list();
if (children == null) {
System.out.println("does not exist or is not a directory");
} else {
for (int i = 0; i < children.length; i++) {
String filename = children[i];
System.out.println(filename);
}
}
//search
Scanner search = new Scanner(System.in);
System.out.print("Search for a song: ");
String music = search.next();
for (int x=0; x<children.length; x++){
if(children[x].equals(music)){
System.out.println(children[x]);
}
}
//Open file
File file = new File("/Users/Runa.C/Music/music/youtubnow.co - Distrion & Alex Skrindo - Lightning [NCS Release].mp3");
Desktop desktop = Desktop.getDesktop();
if(file.exists()) desktop.open(file);
file = new File("/Users/Runa.C/Music/music/youtubnow.co - Distrion & Alex Skrindo - Lightning [NCS Release].mp3");
if(file.exists()) desktop.open(file);
search.close();
}
}
if(children[x].equals(music))has any effect?children[x]andmusicare expected to be strings, perhaps usingchildren[x].equals(music)could help?children[x]andmusicare?String'scontainsmethod within your loop. This method checks if the given argument is contained within the string on which the method is called.