Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

115
Views
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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!