如何在 Java 中停止此越界异常

How can I stop this out of bounds exception in Java

嗨,我想知道如何编写一个 try 和 catch 块来阻止出现以下错误。

java.lang.IndexOutOfBoundsException: Index: 1, Size: 1

我有这个方法,它接受一个句子并将它拆分成一个 ArrayList。然后我用它来将值存储到哈希图中,其中索引 1 是键,后面的词成为值。我使用以下方法将用户输入拆分为一个数组。

私人扫描器reader;

    /**
     * Create a new InputReader that reads text from the text terminal.
     */
    public InputReader()
    {
        reader = new Scanner(System.in);
    }

    public ArrayList<String> getInput() 
    {
        System.out.print("> ");                // print prompt
        String inputLine = reader.nextLine().trim().toLowerCase();

        String[] wordArray = inputLine.split(" ");  // split at spaces

        // add words from array into ArrayList
        ArrayList<String> words = new ArrayList<String>();
        for(String word : wordArray) {
            words.add(word);
        }
        return words;
    }

}

下面的方法使用上面的 class 来检测用户输入。因此,当用户输入 write 时,他们可以写入 hashmap,但如果他们在输入键和值之前按 return,我会得到越界异常。那么我该如何重写下面的方法来避免这种情况呢?

 public void start()
    {

        boolean finished = false;


            printWelcome();
            while(!finished) {
                ArrayList<String> input = reader.getInput();

                if(input.contains("shutdown")) {
                    finished = true;
                }

                if (input.contains("load")) {
                    System.out.println();
                    instruct.readAndFill();
                    System.out.println();
                }            

                if (input.contains("write")) {
                    String key = input.get(1);
                    String value = "";
                    for(int i=2; i<input.size(); i++) {
                        value = value + " " + input.get(i);
                    }
                    instruct.mapWrite(key, value);
                }
            } 
            instructorGoodBye();
        }

抱歉,如果我不够清楚,或者如果我的代码没有达到标准,我现在才学习 java 大约 2 个月。

您收到以下部分代码的错误..

if (input.contains("write")) {
                    String key = input.get(1);// here is the problem..
                    String value = "";
                    for(int i=2; i<input.size(); i++) {
                        value = value + " " + input.get(i);
                    }
                    instruct.mapWrite(key, value);
                } 

在此代码段的第 2 行。 您正在使用索引访问一个值。现在想象一下,您只是在控制台中输入了一个单词。所以你将从 getInput() 方法获得的数组列表的大小为 1。所以..在数组列表中,单词将放在第 0 个位置。(即第一个位置)但你正在访问第二个位置的值.. 那给了你一个债券异常的索引..

basically if the user types in write key value on one line it is fine but if they hit return after write then the error happens.

所以,从根本上说,您缺少的是错误检查。您的程序正在接受用户的输入,并假设它是有效的。 这总是个坏主意

相反,您应该验证从用户那里获得的信息。对于 "write" 块,您可以执行此操作的一种方法是确保您期望存在的元素实际上存在。

首先,我将按如下方式重写您的循环:

while(!finished) {
    List<String> input = reader.getInput();
    if(input.size() == 0) {
        throw new IllegalArgumentException("Must specify command, one of 'shutdown', 'load', 'write'");
    }

    final String command = input.remove(0).toLowerCase();
    // TODO: Make sure command is one of the valid commands!

注意变化:

  1. 分配给 List 而不是 ArrayList 只是一个很好的通用做法。
  2. 检查输入以确保它有多个零元素
  3. 取第一个元素,因为我们不想做 List.contains()。考虑输入 garbage garbage garbage write,显然我们不希望它调用 "write" 命令,它应该被视为无效输入。

最后,我们用它来重写执行命令的条件:

if(command.equals("write")) {
    // Make sure the user put the right stuff in here
    // Since we removed the command from the input already, just make sure what is left is 
    if(input.size() <= 1) {
        throw new IllegalArgumentException("Must specify correct data");
    }
    String key = input.remove(0);
    String value = String.join(" ", input); // Java 8
    instruct.mapWrite(key, value);
}

基本上,修复比抛出新异常并使用 try 和 catch 块更简单。我所要做的就是稍微改变逻辑并使用 if else 语句。

  if (input.contains("write")) {    
                    if(input.size() >=2) {

                        String key = input.get(1);                   
                        String value = "";
                        for(int i=2; i<input.size(); i++) {
                            value = value + " " + input.get(i);
                        }
                        mapWrite(key, value);
                    } else {
                        System.out.println("Please type in the key & value after write all on line");
                    }

                }

到目前为止,根据我从 java 中学到的知识,最好的解决方案通常总是最简单的。感谢所有的帮助,所有评论和试图帮助我的人基本上帮助我想出了这个主意。