title: How can I stop this out of bounds exception in Java
body: <p>Hi I wanted to know how to write up a try and catch block to stop from getting the below error.</p>
  
  <pre><code>java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
  </code></pre>
  
  <p>I have this method which takes a sentence and splits it into an ArrayList. I then use that to store values into a hashmap, where index 1 is the key and the words after become the value. I use the below method to split the user input into an array.</p>
  
  <p>private Scanner reader;</p>
  
  <pre><code>    /**
       * Create a new InputReader that reads text from the text terminal.
       */
      public InputReader()
      {
          reader = new Scanner(System.in);
      }
  
      public ArrayList&lt;String&gt; getInput() 
      {
          System.out.print("&gt; ");                // print prompt
          String inputLine = reader.nextLine().trim().toLowerCase();
  
          String[] wordArray = inputLine.split(" ");  // split at spaces
  
          // add words from array into ArrayList
          ArrayList&lt;String&gt; words = new ArrayList&lt;String&gt;();
          for(String word : wordArray) {
              words.add(word);
          }
          return words;
      }
  
  }
  </code></pre>
  
  <p>and the below method uses the class above to detect user input. So when the user types in write they can write into a hashmap but if they press return before they type in a key and value I get the out of bounds exception. So How can i rewrite the below method to avoid this?</p>
  
  <pre><code> public void start()
      {
  
          boolean finished = false;
  
  
              printWelcome();
              while(!finished) {
                  ArrayList&lt;String&gt; 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&lt;input.size(); i++) {
                          value = value + " " + input.get(i);
                      }
                      instruct.mapWrite(key, value);
                  }
              } 
              instructorGoodBye();
          }
  </code></pre>
  
  <p>Sorry if i wasn't clear enough, or if my code is not up to scratch i have only been learning java for about 2 months now.</p>