【问题标题】:How to properly open a new Scanner and take input如何正确打开新的扫描仪并接受输入
【发布时间】:2016-08-20 21:20:30
【问题描述】:

我最近偶然发现了 JSoup 库,所以我决定通过创建一个 google 查询程序来尝试 hit。

这个想法是输入一个谷歌搜索,输入你想要显示的查询数量,显示它们,然后要求用户再输入一个整数,这是索引显示在链接旁边。

问题是新的 Scanner 永远不会被调用。它打印提示并关闭。

注意:我知道我可以自己去谷歌搜索。我只是在试验这个新的库,它触及了我大脑中让我想进一步研究的部分。

这是代码和输出 -- 抱歉,如果它是草率的。还在学习中……

import java.io.IOException;
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;

    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

        Scanner 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";
        for (Element result : results) {

            index++;
            linkHref = result.attr("href");
            String linkText = result.text();
            String pingResult = index + ": " + linkText + ", URL:: " + linkHref.substring(6, linkHref.indexOf("&"));
            if (pingResult.contains(news)) {
                System.out.println("FOUND " + "\"" + linkText + "\"" + "NO HYPERTEXT FOR NEWS QUERY RESULTS AT THIS TIME. SKIPPED INDEX.");
                System.out.println();
            } else {
                System.out.println(pingResult);
            }
        }
        System.out.println();
        System.out.println();


        goToURL(linkHref, input);
    }

    public static int goToURL(String hRef, Scanner input) {

        try {

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

            int newIndex = input.nextInt();

            for (int i = 0; i < index; i++) {

                if (newIndex == index) {
/*
RUNNING LINUX COMMAND WITH RUNTIME CLASS TO COCANTENATE THE HYPERLINK SUBSTRING
*/
                    Process process = Runtime.getRuntime().exec("xdg-open " + hRef.substring(6, hRef.indexOf("&"))); 
                    process.waitFor();
                    break;
                } else if (newIndex == 0) {
                    System.out.println("Shutting program down.");
                    System.exit(0);
                }
            }
        } catch (Exception e) {
            System.out.println("ERROR while parsing URL");
        }
        return index;
    }
}

这是输出 它在新的 Scanner 接受输入之前停止

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 (@Oracle) | Twitter, URL:: =https://twitter.com/oracle%3Flang%3Den


Enter Index (i.e. 1, 2, etc) you wish to visit, 0 to exit: Shutting program down.

Process finished with exit code 0

如您所见,它直接进入 else 语句来关闭程序。 任何帮助将不胜感激。这是一个有趣的项目,我期待着完成它。

【问题讨论】:

  • 如果您想从standard input 读取数据,请在所有位置使用相同的扫描仪实例。这应该可以解决问题。
  • 好的。我删除了新的 Scanner 并将其放入 goToURL 方法的参数中(String hRef,Scanner 输入)。它允许我输入一个数字,但程序现在在输入后停止。但是,嘿,进步!
  • 问题是每当你关闭Scanner实例时,你也会关闭底层的InputStream(也就是stdin),所以后面的Scanner userInput = new Scanner(System.in)依赖于一个已经关闭的InputStream .结果:您不再需要输入! ;)
  • 为了进一步混淆评论,我很乐意编辑我的问题以包括现在保持打开的扫描仪。 :)
  • 删除了 else 语句。

标签: java hyperlink jsoup java.util.scanner


【解决方案1】:

根据 SO 团队成员的建议,我问为什么 Scanner 不要求输入。从技术上讲,我解决了程序停止获得输入的问题。尽管在实际未处理输入的情况下仍然存在问题,但之前的问题已解决,这是我的解决方案。

我没有关闭原来的 Scanner,而是将 Scanner 作为参数添加到我的“goToURL”方法中。我还删除了关闭程序的 else 语句,因为允许程序继续运行的输入仍然有问题。尽管如此,这是至少解决原始问题的“工作”代码。

此外,我将 String 元素 (pingResult) 放入 ArrayList 以改进 goToURL 方法中的循环结构。我觉得这是一种使用简单数据结构来访问元素的好方法:

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;

    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

        Scanner 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";
        /*
        THIS WILL ADD THE pingResult STRINGS TO AN ARRAYLIST
        */
        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();
        System.out.println();


        goToURL(linkHref, input, displayResults);
    }

    public static int goToURL(String hRef, Scanner input, ArrayList<String> resultList) {

        try {

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

            index = input.nextInt();

            for (String string : resultList) {

                if (string.startsWith(Integer.toString(index))) {

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

【讨论】:

    猜你喜欢
    • 2017-09-23
    • 1970-01-01
    • 1970-01-01
    • 2016-06-20
    • 1970-01-01
    • 1970-01-01
    • 2015-10-02
    • 2017-09-04
    • 1970-01-01
    相关资源
    最近更新 更多