BigBoi
BigBoi

Reputation: 11

return statement being skipped inside 2 loops

I am using the following method that i found online and tweaked to find files in a given directory using only the file's name:

public static void main(String[] args)
{
   Scanner scan = new Scanner(System.in);
   System.out.println("Enter the file to be searched.. " );
   String name = scan.next();
   System.out.println("Enter the directory where to search ");
   String directory = scan.next();
   System.out.println(findFile(name,new File(directory)));
}

public static String findFile(String name,File file)
{
    String correctFilePath = null;
    ArrayList<String> possiblePaths = new ArrayList<String>();
    File[] list = file.listFiles();
    String nameToFind = "anyname";
    if(list!=null)
        for (File fil : list)
        {
            if (fil.isDirectory())
            {
                findFile(name,fil);
            } else if (name.equalsIgnoreCase(fil.getName()))
            {
                possiblePaths.add(fil.getParent());
            }
        }
    // Here, all the files containing the name of the file that I am looking
    // for have been already added to the ArrayList.
    // However, I know what the ending of the path is,
    // which is what I am checking in the following loops
    String filePath;
    for (int i = 0; i < possiblePaths.size(); i++)
    {
        filePath = possiblePaths.get(i);
        for (int j = 0; j < nameToFind.length(); j++)
        {
            if (filePath.charAt(filePath.length()     - (j + 1)) ==
                nameToFind.charAt(nameToFind.length() - (j + 1))    )
            {
                if (j == nameToFind.length() - 1)
                {
                    correctFilePath = filePath;
                    return correctFilePath;
                }
            }
        }
    }
    return correctFilePath;
}

Right now, what happens is that once the file is found and correctFilePath = filePath is executed, the return statement is being skipped, and I am brought back to the beginning of the i loop, with correctFilePath = null. How could i fix this?

Upvotes: 0

Views: 42

Answers (1)

BigBoi
BigBoi

Reputation: 11

So in the end, i took away that return statement and the correctFilePath = filePath; statement, and replaced both by an indication of the desired String's position inside of the ArrayList, which i set to static.

Upvotes: 1

Related Questions