完成java上的搜索逻辑

时间:2013-12-10 11:18:56

标签: java

当数组argi有多个分区时,它只会从数组的第二个url开始查找单词,但为什么呢?请在代码中纠正它。这部分是: 我通过url中的标题定期进行搜索:

private final Pattern TITLE = Pattern.compile("\\<title\\>(.*)\\<\\/title\\>", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);

这里的搜索逻辑:

public String search(String url, String someword) {

                    try {
                        InputStreamReader in = new InputStreamReader(new URL(url).openStream(),"UTF-8");
                        StringBuilder input = new StringBuilder();
                        int ch;
                        while ((ch = in.read()) != -1) {
                            input.append((char) ch);
                        }
                        if (Pattern.compile(someword, Pattern.CASE_INSENSITIVE).matcher(input).find()) {
                            Matcher title = TITLE.matcher(input);
                            if (title.find()) {
                                return title.group(1);
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (PatternSyntaxException e) {
                        e.printStackTrace();
                    }
                    return null;
                }

            String[] argi = {"http://localhost:8080/site/dipnagradi","http://localhost:8080/site/contacts"};

                                for (int i = 0; i < argi.length; i++) {

                                    String result = search(argi[i], word);

                                    if (result != null) {


            str = "Search phrase " + "<b>"+ word + "</b>" + " have found " + "<a href=\"" + argi[i] + "\">" + result + "</a>"+ "<p></p>";

                     }
                                    else{
                                        str="Search word not found!";
                                    }    

                                    if (word == null||word=="") {

                                        str = "Enter a search word!";


                                    }
                            }
                            return null;

                 }

2 个答案:

答案 0 :(得分:0)

使用if (word == null || word.isEmpty()),(对于初学者)从不在java中的==比较中使用Object

此外,要获得更详细的答案,您确实需要发布输入和预期输出。以及`search()的作用。

答案 1 :(得分:0)

不要对String使用'=='运算符,因为String是一个Object,并使用equals方法进行比较。而是使用:if(!"".equals(word){}