【问题标题】:Java ArrayList IndexOutOfBoundsException [closed]Java ArrayList IndexOutOfBoundsException [关闭]
【发布时间】:2014-08-21 00:45:30
【问题描述】:

我正在尝试在 Java 中读取某个文件每当我从脚本中读取一行代码时,它都会显示:

Welcome to DrJava.  Working directory is /Users/anu-lion
> run WebCrawler02
!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="ena
java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
    at java.util.ArrayList.rangeCheck(ArrayList.java:635)
    at java.util.ArrayList.get(ArrayList.java:411)
    at WebCrawler02.main(WebCrawler02.java:147)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
> 

我知道这个错误是编码无法达到特定索引时引起的,但我目前不知道如何解决。

这是我的编码。

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import javax.swing.JOptionPane;

public class WebCrawler02 {
            ArrayList<String> pagesVisited;
            ArrayList<String> pagesToVisit;

            public static URL getStartingURLFromUser() {
                        // This method gets the URL from user.
                        // Initializes the URL string.
                        URL startingURL = null;
//                     String startingString = "http://www.cs.uwec.edu/~stevende/cs145testpages/default.htm";
                         String startingString = JOptionPane.showInputDialog(null, "Enter a valid URL:");
                        startingString.toLowerCase();
                        // catches errors in URL.
                        try {
                                    startingURL = new URL(startingString);
                        } catch (MalformedURLException e) {
                                    System.out.println("Bad URL");
                                    System.exit(0);
                        }
                        return startingURL;
            }

            public static String htmlReader(URL webURL) {
                        // Initializes the strings.
                        String htmlContent = null;
                        // Reading the file.
                        // This try/catch block reads in a file with a reader and creates a
                        // continuous string.
                        try {
                                    URLConnection con = webURL.openConnection();
                                    InputStream is = con.getInputStream();
                                    BufferedReader br = new BufferedReader(new InputStreamReader(is));
                                    String line = br.readLine();
                                    while (line != null) {
                                                htmlContent = htmlContent + line + " ";
                                                line = br.readLine();
                                    }
                                    br.close();
                        } catch (MalformedURLException e) {
                                    System.out.println("Bad URL");
                                    System.exit(0);
                        } catch (FileNotFoundException e) {
                                    e.printStackTrace();
                                    System.out.println("File not found.");
                        } catch (IOException e) {
                                    e.printStackTrace();
                                    System.out.println("after try/catch");
                        }
                        return htmlContent;
            }

            public static ArrayList<String> linkParser(String htmlContents) {
                        // Initializes the strings, boolean, variables and arraylist.
                        ArrayList<String> listOfLinks = new ArrayList<String>();
                        int i = 0;
                        int k = 0;
                        boolean search = true;
                        String URL = "";
                        // This loop creates an array list of URL's.
                        while (search == true) {
                                    i = htmlContents.indexOf("HREF=", k) + 6;
                                    k = htmlContents.indexOf("\">", i);
                                    URL = htmlContents.substring(i, k);
                                    listOfLinks.add(URL);
                                    if (i == htmlContents.lastIndexOf("HREF=") + 6) {
                                                search = false;
                                    }
                        }
                        return listOfLinks;
                        // System.out.println(htmlContents);
            }
            public static boolean isBrokenLink(URL currentURL, String theHREF) {
                        // Initializes the strings, boolean, variables and arraylist.
                        Boolean isbroken = false;
                        try {
                                    URL baseURL = new URL(currentURL, theHREF);
                                    URLConnection con = currentURL.openConnection();
                                    HttpURLConnection httpProtocol = (HttpURLConnection) con;
                                    httpProtocol.getResponseCode();
                                    int httpPro = httpProtocol.getResponseCode();
                                    if (httpPro != 200) {
                                                isbroken = true;
                                    }
                        } catch (MalformedURLException e) {
                                    isbroken = true;
                                    System.out.println("Bad URL1");
                        } catch (FileNotFoundException e) {
                                    isbroken = true;
                                    e.printStackTrace();
                                    System.out.println("File not found.");
                        } catch (IOException e) {
                                    isbroken = true;
                                    e.printStackTrace();
                                    System.out.println("after try/catch");
                        }
                        return isbroken;
            }

            public static void displayBrokenLinkReport(
                                    ArrayList<ArrayList<String>> brokenLinks) {
                        System.out.println("Broken Link Report: \n");
                        for (int j = 0; j < brokenLinks.size(); j++) {
                                    for (int i = 0; i < brokenLinks.get(j).size(); i++) {
                                                if (j == 0) {
                                                            System.out.println("Page " + brokenLinks.get(j).get(i));
                                                } else {
                                                            System.out.println("Broken link "
                                                                                    + brokenLinks.get(j).get(i));
                                                }
                                    }
                        }
            }

            public static void main(String[] args) {
                        // Initializes the arraylists and the array<arraylist
                        ArrayList<URL> pagesVisited = new ArrayList<URL>();
                        ArrayList<URL> pagesToVisit = new ArrayList<URL>();
                        ArrayList<String> listOfLinks = null;
                        ArrayList<String> badLinks = null;
                        ArrayList<ArrayList<String>> brokenLinks = new ArrayList<ArrayList<String>>();
                        int i = 0;
                        // calls the getStartingURLFromUser method which returns the string.
                        pagesToVisit.add(getStartingURLFromUser());
                        while (!pagesToVisit.isEmpty()) {
                                    URL baseURL = pagesToVisit.get(0);
                                    pagesVisited.add(baseURL);
                                    pagesToVisit.remove(0);
                                    // calls the htmlReader method which returns the string.
                                    String htmlContent = htmlReader(baseURL);
                                    // calls the linkParser method which returns the array list.
                                    listOfLinks = linkParser(htmlContent);
                                    // calls the isBrokenLink method which returns the string.
                                    for (i = 0; i <= (listOfLinks.size()); i++) {
                                                boolean isBL = isBrokenLink(baseURL, listOfLinks.get(i));
                                                System.out.println(listOfLinks.get(i) + "a");
                                                if (isBL) {
                                                            System.out.println(listOfLinks.get(i));
                                                            badLinks.add(listOfLinks.get(i));
                                                } else {
                                                            // catches errors in URL.
                                                            URL nextURL = null;
                                                            try {
                                                                        nextURL = new URL(baseURL, listOfLinks.get(i));
                                                                        if (!pagesVisited.contains(nextURL)) {
                                                                                    pagesToVisit.add(nextURL);
                                                                        }
                                                            } catch (MalformedURLException e) {
                                                                        e.printStackTrace();
                                                                        System.out.println("Bad URL2");
                                                            }
                                                }
                                    }
                                    brokenLinks.add(badLinks);
                        }
                        displayBrokenLinkReport(brokenLinks);
            }
}

提前致谢。

【问题讨论】:

  • 您的输入是什么导致您出现此错误?
  • 问题很明显:您试图从长度为 1 的 ArrayList 中提取索引 1(因此唯一有效的索引是 0)。您需要做更多的工作来显示导致问题的代码区域 - 异常会告诉您,但没有多少人会检查您的所有代码来为您找出问题。
  • 错误出现在第 147 行,无论它在哪里。
  • 这是一个容易调试的问题。你试过什么??

标签: java arraylist


【解决方案1】:

for (i = 0; i &lt;= (listOfLinks.size()); i++) 我想问题出在这里,尝试使用普通的&lt; 而不是&lt;=listOfLinks.size() 应该是你的listOfLinks 的大小,并且由于它是从零开始索引的,所以最后一个元素的索引应该是listOfLinks.size()-1

【讨论】:

  • 另一种说法相同的事情:0是第一个元素的索引,1是第二个元素的索引,listOfLinks.size() - 1是最后一个元素的索引,并且listOfLinks.size() 是最后一个元素之后的索引,即超出列表范围(解释了异常的名称)
  • @Volune: +1,这是表达这个的好方法 =)
【解决方案2】:
for (i = 0; i <= (listOfLinks.size()); i++) {

应该是

for (i = 0; i < (listOfLinks.size()); i++) {

在第 145 行。

【讨论】:

    猜你喜欢
    • 2016-03-22
    • 2018-12-03
    • 1970-01-01
    • 2016-04-11
    • 2013-10-28
    • 1970-01-01
    • 2014-01-14
    • 2015-11-07
    相关资源
    最近更新 更多