title: Array index out of bounds exception java while using loops
body: <p>Every few runs of my program it gives me the error</p>
  
  <pre><code>     at outlab6.Battleship.setShips(Battleship.java:75)
       at outlab6.Battleship.setBoard(Battleship.java:35)
  </code></pre>
  
  <p>But I thought that I was already setting the code up so that those shouldn't happen.  Can someone tell me what I did wrong and why it's not ignoring the possibilities that make that possible?</p>
  
  <pre><code>package outlab6;
  
  import java.util.Scanner;
  
  public class Battleship {
    private int rows;
    private int cols;
    private Spot spot[][];
    Scanner input = new Scanner(System.in);
  
    public  Battleship(int rows, int cols){
      this.rows = rows;
      this.cols = cols;
    }
    public void setBoard(){
      spot = new Spot[rows][cols];
      for(int i = 0; i &lt; rows; i++){
        for( int j = 0; j &lt; cols; j++){
          spot[i][j] = new Spot();
        }
      }
      //setup board to be completely empty
      for(int i = 0; i &lt; rows; i++){
        for(int j = 0; j &lt; cols; j++){
          spot[i][j].setShip(0);
        }
      }
      //   //test code
      //   for(int i = 0; i &lt; rows; i++){
      //     for(int j = 0; j &lt; cols; j++){
      //       System.out.print(spot[i][j].getShip());
      //     }
      //     System.out.println();
      //   }
      setShips();
    }
    public void printBoard(boolean active){
  
  
    }
    public boolean over() {
  
      return false;
    }
    public void makeGuess() {
      input.nextInt();
  
    }
    public void printStatistics() {
  
  
    }
    public void setShips(){
      //this method creates and places the ships
      //start with carrier and move on down
      for(int i = 5; i &gt; 1; i--){
        int col;
        int row;
        boolean valid = false;
        //set a direction
        int direction = (int)(Math.random()*2)+1;
        //System.out.println(direction);
        //get a valid spot
        while(!valid){
          //generate a location
          int chosenRow = (int)(Math.random()* rows)+1;
          int chosenCol = (int)(Math.random()* cols)+1;
          System.out.println("Row:" + chosenRow);
          System.out.println("Col:" + chosenCol);
          //check to see if spot is open
  
          //for horizontal ships
          if(chosenCol + i &lt; cols){
            for(int j = 0; j &lt; i; j++){
              if(spot[chosenRow][chosenCol + i].getShip() == 0){
                valid = true;
              }else{
                valid = false;
              }
            }
          }else{
            //go through again
          }
  
        }
      }
    }
  }
  </code></pre>