-1

I don't seem to be getting any other errors except this one: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2 I looked it up and it says i'm trying to get a value that isn't in my array list. I'm not sure where I went wrong with this.

import java.util.*;
 class DebugNine1
{
 public static void main(String[] args)
 {
  Scanner input = new Scanner(System.in);
  String[][] books = new String[6][2]; 
  books[0][0] = "Ulysses";
  books[0][1] = "James Joyce";
  books[1][0] = "Lolita";
  books[1][1] = "Vladimir Nabokov";
  books[2][1] = "Huckleberry Finn";
  books[2][1] = "Mark Twain";
  books[3][0] = "Great Gatsby";
  books[3][2] = "F. Scott Fitzgerald";
  books[4][0] = "1984";
  books[4][1] = "George Orwell";
  books[5][5] = "Sound and the Fury";
  books[5][1] = "William Faulkner";

  String entry,
     shortEntry,
     message ="Enter the first three characters of a book title omitting \"A\" or \"The\" ";
  int num, x;
  boolean isFound = true;
  while(isFound)
  {
     System.out.println(message);
     entry = input.next();
     shortEntry = entry.substring(0,3);
     for(x = 0; x < books.length; ++x)
        if(books[x][0].startsWith(entry))
        {
           isFound = false;
           System.out.println(books[x][0] + " was written by " + books[x][1]);
           x = books.length;
        }
     if(isFound)
        System.out.println("Sorry - no such book in our database");
    }
 }
}
Nitro
  • 87
  • 7

1 Answers1

0

The problem is in the following two lines:

books[3][2] = "F. Scott Fitzgerald";
...
books[5][5] = "Sound and the Fury";

Change them to

books[3][1] = "F. Scott Fitzgerald";
...
books[5][0] = "Sound and the Fury";

Note that your array has been declared as follows:

String[][] books = new String[6][2];

which means you can have only 0 or 1 as the index value for the second dimension.

In addition to the problems mentioned above, you should also consider changing the first of the following two lines otherwise you will have null at books[2][0]:

books[2][1] = "Huckleberry Finn";
books[2][1] = "Mark Twain";

Change it to

books[2][0] = "Huckleberry Finn";
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110