What I want to do is set a String called nameWithYear to be equal to be movies[0] + "(" + movies[1]+")" (So "Movie Title (Year)") from text being parsed off a CSV.
Whenever I try, I am experiencing an issue where I keep on getting an array out of bounds error. I tried setting the string equal to only movies[0], it works with success. When I try to set it to movies[1] by itself, it fails. I can do a System.out that includes element [1], and it outputs just fine with no issues. So in other words, for some reason, I can only include element[0] in the string and not element[1]. So I am assuming it has something to do with declaring the value for the string. Just not sure what.
The code is as follows:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class CSVParsing {
public String parseCSV() {
String csvFile = "C:\\Users\\RAY\\Desktop\\movies.csv";
BufferedReader br = null;
String nameWithYear = new String();
String line = "";
String csvSplitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
if (line.charAt(0) == '"')
{
csvSplitBy = "\",";
}
else
{
csvSplitBy = ",";
}
String[] movies = line.split(csvSplitBy);
nameWithYear = ""+ movies[0]+" ("+movies[1]+")";
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return nameWithYear;
}
public static void main (String[] args)
{
CSVParsing obj = new CSVParsing();
String testString = obj.parseCSV();
}
}
Note that it is not 100% complete, I am testing it in small chunks to make sure it is doing everything as I want it to do.
UPDATE: Found out that it was related to blank year entries as part of the CSV. How do I handle that? The program cuts off once it finds the year entry to be blank.
UPDATE 2: I solved it with my own but of research. I am taking the results after the split() and putting them into an ArrayList. That way, I could handle blank entries in the year column by replacing them with another value.
System.out.println(Arrays.toString(movies));before the linenameWithYear = ""+ movies[0]+" ("+movies[1]+")";and see what he prints if you run your program. The output for an array with to entries looks like this:[array with, two entries].moviearray.