gpt4 book ai didi

Java URL 方法未正确填充递归

转载 作者:行者123 更新时间:2023-12-02 13:18:08 25 4
gpt4 key购买 nike

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

}
}

所以这个程序应该接受用户输入的 url 链接并以 html 形式打印所有超链接,“a href”到结束“a”标记。如果 url 最初有效,则此代码将执行此操作。但是,如果输入了无效的 url,系统会捕获它,并且 Urlpprompt 方法会调用自身,当该方法在无效输入后调用自身,然后在递归期间输入有效的 URL 时,我会在第 24 行收到空指针异常...怎么办?我在递归过程中得到 URLPrompt 方法来准确填充变量 pageLocation?

最佳答案

递归调用应该是return URLPrompt()

顺便说一句:我不会为此目的使用递归(这只是浪费堆栈帧),只是一个简单的 while 循环。

关于Java URL 方法未正确填充递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43701492/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com