简体   繁体   中英

Java URL method not filling properly with recursion

import java.util.Scanner;
import java.net.MalformedURLException;
import java.net.URL;
import java.io.IOException;

public class Main {

    // takes user input and validates
    public static URL URLPrompt() throws MalformedURLException {
        URL pageLocation = null;
        Scanner in = new Scanner(System.in);
        System.out.println("Please enter a webpage URL to find all it's links: ");
        try {
            pageLocation = new URL(in.nextLine());
        } catch (MalformedURLException exception) {
            System.out.println("Invalid URL");
            URLPrompt();
        }
        return pageLocation;
    }

    public static void main(String[] args) throws MalformedURLException, IOException {
        Scanner in = new Scanner(System.in);
        URL pageLocation = URLPrompt();
        Scanner scan = new Scanner(pageLocation.openStream());
        while (scan.hasNext()) {
            String webFile = scan.nextLine();
            // Searches for all hyperlinks in <a href=> </a> form
            if (webFile.contains("<a href=") && webFile.contains("</a>")) {
                int x = webFile.indexOf("<a href=");
                int y = webFile.indexOf("</a>");
                String link = webFile.substring(x, y + 4);
                System.out.printf("%s\n", link);

            }
        }
        scan.close();
        in.close();

    }
}

So this program is supposed to take a user inputted url link and print out all of the hyperlinks in html form, "a href" to the closing "a" tag. This code does just that if the url is valid initially. However, if an invalid url is input the system catches it and the Urlprompt method calls itself, when the method calls itself after an invalid input and then a valid URL is input during recursion I get a nullpointer exception on line 24... How can I get the URLPrompt method to accurately fill the variable pageLocation during recursion?

The recursive call should be return URLPrompt() .

BTW: I wouldn't use recursion for this purpose (it's just a waste of stack frames), just a simple while loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM