-1

I'm trying to build a Binary Search Tree. Below in my main method which reads from a file and inserts into the BST. However, I am getting an index out of bounds error and cannot figure out how to fix it. Any suggestion/solutions as to how it can be fixed?

public static void main(String[] args)
{
BinarySearchTree bst = new BinarySearchTree();
 
try
{
// you may modify the filepath, but not the filename
File file = new File("C:\\Users\\mbash\\Documents\\netflix_titles_alternative.csv");
     
Scanner token = new Scanner(file);
token.nextLine();                       
while(token.hasNext())                  
{
String line = token.nextLine();              
String tmp[] = line.split(";"); 
String type = tmp[0];
String title = tmp[1];
int releaseYear = Integer.parseInt(tmp[2]);
bst.insert(type, title, releaseYear);
}
token.close();
}
     
catch(FileNotFoundException e)
{
System.out.println(e.getMessage());
System.exit(0);
}
  • 2
    Print or debug what your line look like. – Just another Java programmer May 13 '22 at 13:10
  • if the length is 1, the only valid index is 0. Don't use an invalid index – Stultuske May 13 '22 at 13:11
  • This is an error message you can easily debug yourself. Step through the code with a debugger and inspect variables like `tmp`, and also check the stack trace. Your `catch` is not adding anything to the default behaviour of when an exception occurs, so I would just remove your `try/catch` wrapper -- it will be easier to debug. Indenting code is also a great help to get insight into code. You should try it. – trincot May 13 '22 at 13:21

1 Answers1

0

An indexoutofboundsexception occurs when you try to access an element of an array that does not exist.

Apparently, you have 1 line in your file that doesn't contain a title.

You can add a condition for example to make sure that tmp.length is greater than 3 each time you want to access tmp[0], tmp[1], and tmp[2].

    while(token.hasNext())                  
{
String line = token.nextLine();              
String tmp[] = line.split(";"); 
if (tmp.length >= 3) {
String type = tmp[0];
String title = tmp[1];
int releaseYear = Integer.parseInt(tmp[2]);
bst.insert(type, title, releaseYear);
}
    }