When i try to print out each value in my csv file using the below code:
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import com.opencsv.CSVReader;
import com.opencsv.exceptions.CsvValidationException;
public class searchBook {
public static void main(String[] args)throws IOException, CsvValidationException {
Main a = new Main();
String fileName = "bookData.csv";
try (var fr = new FileReader(fileName, StandardCharsets.UTF_8);
var reader = new CSVReader(fr)) {
String[] nextLine;
while ((nextLine = reader.readNext()) != null) {
Integer i = 0;
for (String e : nextLine) {
String[] bookInfo = nextLine[i].split(",", -2);
i++;
System.out.println(bookInfo[0]);
String type = bookInfo[0];
String title = bookInfo[1];
String author = bookInfo[2];
String ISBN = bookInfo[3];
String pubDate = bookInfo[4];
String illustrator = bookInfo[5];
String narrator = bookInfo[6];
if(a.book.equals(title) || a.book.equals(author) || a.book.equals(ISBN) || a.book.equals(illustrator) || a.book.equals(narrator)) {
String typeSaved = bookInfo[0];
String titleSaved = bookInfo[1];
String authorSaved = bookInfo[2];
String ISBNSaved = bookInfo[3];
String pubDateSaved = bookInfo[4];
String illustratorSaved = bookInfo[5];
String narratorSaved = bookInfo[6];
}
}
}
}
} public Object typeSaved, titleSaved, authorSaved, ISBNSaved, pubDateSaved, illustratorSaved, narratorSaved;
}
while using this csv file:
Book,The_Hunger_Games,Suzanne_Collins,9780439023481,14/10/2008,N/A,N/A,No
Comic_book,Astonishing_X-Men,Warren_Ellis,N/A,2004,Simone_Bianchi,N/A,No
Audio_book,Never_Finished,David_Goggins,N/A,06/12/2022,N/A,David_Goggins,No
i am met with the error code: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1 at searchBook.main(searchBook.java:29)
Is there a way to fix this?
I attempted to remove all the spaces in the csv file incase that could possibly be the issue but this had no effect.
Also since its due to the index value being 1 or greater when i tried to print out just the 0 value it printed out everything in the csv file.
Any help would be appreciated!