【问题标题】:Java program closing before Scanner can take input 2nd time aroundJava 程序在 Scanner 可以第二次接受输入之前关闭
【发布时间】:2016-04-26 22:10:20
【问题描述】:

我正在尝试使用 JSoup,但无法让我的 Scanner 进行第二次复飞。它直接跳到我的 catch 语句。

这是程序的描述:

我将谷歌搜索词作为用户输入(字符串)。接下来,我询问用户希望查看的查询项的数量,并输入一个整数。

我遍历返回的每个元素并将其添加到 ArrayList。控制台上显示的字符串由索引、链接文本和超链接组成。

然后我想询问用户他们想进入哪个索引以打开指向该链接的浏览器窗口。这是通过使用 Runtime 类将 hRef 字符串与 Linux 终端命令“xdg-open”共同连接来完成的。

在询问将选择哪个索引之前,它运行良好。

这是我的代码:

/**
 * Created by christopher on 4/26/16.
 */

import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;


public class GoogleSearchJava {

    static int index;
    static String linkHref;
    static Scanner input;

    public static final String GOOGLE_SEARCH_URL = "https://www.google.com/search";

    public static void main(String[] args) throws IOException {

        //GET INPUT FOR SEARCH TERM

        input = new Scanner(System.in);
        System.out.print("Search: ");
        String searchTerm = input.nextLine();
        System.out.print("Enter number of query results: ");
        int num = input.nextInt();

        String searchURL = GOOGLE_SEARCH_URL + "?q=" + searchTerm + "&num=" + num;

        //NEED TO DEFINE USER AGENT TO PREVENT 403 ERROR.
        Document document = Jsoup.connect(searchURL).userAgent("Mozilla/5.0").get();

        //OPTION TO DISPLAY HTML FILE IN BROWSWER. DON'T KNOW YET.
        //System.out.println(doc.html());

        //If google search results HTML change the <h3 class="r" to <h3 class ="r1"
        //need to change below stuff accordingly
        Elements results = document.select("h3.r > a");

        index = 0;
        String news = "News";
        ArrayList<String> displayResults = new ArrayList<>();
        for (Element result : results) {
            index++;
            linkHref = result.attr("href");
            String linkText = result.text();
            String pingResult = index + ": " + linkText + ", URL:: " + linkHref.substring(6, linkHref.indexOf("&")) + "\n";

            if (pingResult.contains(news)) {
                System.out.println("FOUND " + "\"" + linkText + "\"" + "NO HYPERTEXT FOR NEWS QUERY RESULTS AT THIS TIME. SKIPPED INDEX.");
                System.out.println();
            } else {
                displayResults.add(pingResult);
            }
        }
        for(String urlString : displayResults) {
            System.out.println(urlString);
        }
        System.out.println();

        goToURL(input, displayResults);
    }
    public static int goToURL(Scanner input, ArrayList<String> resultList) {

        int newIndex = 0;

        try {

            System.out.print("Enter Index (i.e. 1, 2, etc) you wish to visit, 0 to exit: ");

            newIndex = input.nextInt();
            input.nextLine();

            for (String string : resultList) {

                if(string.startsWith(String.valueOf(newIndex))) {

                    Process process = Runtime.getRuntime().exec("xdg-open " + string.substring(6, string.indexOf("&")));
                    process.waitFor();
                }
            }
        } catch (Exception e) {
            System.out.println("ERROR while parsing URL");
        }
        return newIndex;
    }
}

这里是输出注意我输入“1”后它是如何停止的 不,我还没有注意按“0”:

Search: Oracle
Enter number of query results: 3
1: Oracle | Integrated Cloud Applications and Platform Services, URL:: =http://www.oracle.com/

2: Oracle Corporation - Wikipedia, the free encyclopedia, URL:: =https://en.wikipedia.org/wiki/Oracle_Corporation

3: Oracle on the Forbes America's Best Employers List, URL:: =http://www.forbes.com/companies/oracle/


Enter Index (i.e. 1, 2, etc) you wish to visit, 0 to exit: 1
ERROR while parsing URL

Process finished with exit code 0

【问题讨论】:

  • 另请参阅When Runtime.exec() won't,了解有关正确创建和处理流程的许多好技巧。然后忽略它引用exec并使用ProcessBuilder创建进程。

标签: java jsoup java.util.scanner runtime.exec


【解决方案1】:

ERROR while parsing URL 提示错误来自

try {

    System.out.print("Enter Index (i.e. 1, 2, etc) you wish to visit, 0 to exit: ");

    newIndex = input.nextInt();
    input.nextLine();

    for (String string : resultList) {

        if(string.startsWith(String.valueOf(newIndex))) {

            Process process = Runtime.getRuntime().exec("xdg-open " + string.substring(6, string.indexOf("&")));
            process.waitFor();
        }
    }
} catch (Exception e) {
    System.out.println("ERROR while parsing URL");
}

我不在 Linux 上工作,所以我无法对其进行测试,但我怀疑您的 url 不应该以 = 开头(您会注意到您的控制台包含 URL:: =... 而您的打印语句没有这个= 所以它是您尝试访问的地址的一部分)。

所以将.substring(6, hRef.indexOf("&amp;")) 6 更改为7


其他问题是hRef 设置为linkHref,这将是您选择的谷歌的最后一个结果。您可能应该创建自己的类来存储正确的 href 及其描述,或者传递代表您选择的 &lt;a ...&gt;..&lt;/a&gt; 元素的 Element 列表(您也不需要根据 1: ... 格式检查列表中的元素,如果您想将 1 映射到索引 0、2 到索引 1 等等,只需使用 list.get(index - 1)


目前的最后一条建议是,您可以使用此处How to open the default webbrowser using java 描述的解决方案将代码更改为更加独立于操作系统,而不是尝试执行xdg-open

【讨论】:

  • 我从上面的链接中获得了桌面类代码,但我不确定如何实现您对 linkHRef 变量的建议。
  • @IRGeekSauce 我试着简化一下你的代码。你可以在这里找到它pastebin.com/VTNey8H8(我不想在这里添加完整的解决方案,因为它会使这个答案过于宽泛)。
  • 继续在此处发布您的代码。我试了一下,效果很好。我很乐意接受你的回答。 :)
  • 一个问题,不过。如果我将数字更改为 5,它会给我 8 个查询结果。 ??????但你的回答仍然回答了我最初的问题。
  • @IRGeekSauce 我不确定你的意思。如果我设置int num = 5;,那么您的查询将添加&amp;num=5 参数,该参数应将最大结果设置为5。
猜你喜欢
  • 2013-03-03
  • 1970-01-01
  • 2012-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-21
  • 2020-11-11
  • 1970-01-01
相关资源
最近更新 更多