'How to fix Index 1 out of bounds for length 1 error [duplicate]
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);
}
Solution 1:[1]
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);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | haifa zoghlami |