Hrittik Chatterjee
Hrittik Chatterjee

Reputation: 68

How to look through an array

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(); 
    }
}



Upvotes: 0

Views: 82

Answers (1)

Maxim Bravo
Maxim Bravo

Reputation: 75

Instead of:

if (children[x].equals(music))

You can use:

if (children[x].contains(music))

According to: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#contains(java.lang.CharSequence)

Returns true if and only if this string contains the specified sequence of char values.

Upvotes: 1

Related Questions