字符串索引超出范围:-1 在拥挤的 'if' 语句中

String index out of range: -1 within a crowded 'if' statement

我是 运行 一个程序,它解析网站上的文本,然后在从 HTML 标记中清除后对包含所有文本的字符串进行拼写检查。

一旦拼写检查器到达字符串的末尾,它就会 returns 这个异常。 我看到了类似的问题,这些问题通过在 "if" 语句中将索引设置为大于 0 来解决,但我已经努力解决这个问题一段时间了,希望能得到一些帮助来解决这个问题。

抛出异常:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
    at java.lang.String.substring(Unknown Source)
    at ParseCleanCheck.checkWord(ParseCleanCheck.java:173)
    at ParseCleanCheck.SpellChecker(ParseCleanCheck.java:101)

Java 第 173-175 行是单词被去除所有标点符号的地方:

if (length > 2 && word.substring(length - 2).equals(",\"") || word.substring(length - 2).equals(".\"")
                || word.substring(length - 2).equals("?\"") || word.substring(length - 2).equals("!\"")) {
            unpunctWord = word.substring(0, length - 2);

下面记录了第 101 行,我添加了相关的周围代码,这些代码可能是抛出的异常的一部分

String user_text = "";
user_text = cleanString;
while (!user_text.equalsIgnoreCase("q")) {
                // check if necessary or if cleanString still works
                // PageScanner();
                user_text = cleanString;
                String[] words = user_text.split(" ");

                int error = 0;

                for (String word : words) {
                    suggestWord = true; // ~~~ Line 101 ~~~~
                    String outputWord = checkWord(word);

                    if (suggestWord) {
                        System.out.println("Suggestions for " + word + " are:  " + suggest.correct(outputWord) + "\n");
                        error++;
                    }
                }

                if (error == 0 & !user_text.equalsIgnoreCase("q")) {
                    System.out.println("No mistakes found");
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
            System.exit(-1);
        }

你的问题是如果条件你应该改变它,你只检查第一个条件是否length > 2

if (length > 2 && word.substring(length - 2).equals(",\"") 
        || word.substring(length - 2).equals(".\"")
        || word.substring(length - 2).equals("?\"") 
        || word.substring(length - 2).equals("!\"")) {
            unpunctWord = word.substring(0, length - 2);

更改为:

if (length > 2 
        && (word.substring(length - 2).equals(",\"") 
        || word.substring(length - 2).equals(".\"")
        || word.substring(length - 2).equals("?\"") 
        || word.substring(length - 2).equals("!\""))) {
        unpunctWord = word.substring(0, length - 2);