I am trying to find the shortest title in a file using java programming. I am working with a CSV file. It has Rotten Tomato ratings of movies with Robert De Niro. There are 87 records. Each record has Year, Rating, Title. Here is a link to the file if that helps: https://people.sc.fsu.edu/~jburkardt/data/csv/deniro.csv. I have written the code but i keep getting an error in the output. I can't seem to figure out where the problem is.
I used this code:
private static void summary(String summaryCsv) throws MalformedURLException,
IOException {
URL website = new URL("https://people.sc.fsu.edu/~jburkardt/data/csv/deniro.csv");
Scanner inputStream = new Scanner(new InputStreamReader(website.openStream()));
String[] csvData = new String[1024];
int i = 0, j = 0;
String[] title = new String[1024];
while (inputStream.hasNextLine()) {
String s = inputStream.nextLine();
String[] strArray = s.split(", ");
if (strArray.length == 3) {
title[j] = strArray[2];
}
csvData[i++] = s;
j++;
}
inputStream.close();
System.out.println("Total number of records: " + getLength(csvData));
System.out.println("Shortest title: " + shortest(title));
}
public static <T> int getLength(T[] arr) {
int count = 0;
for (T el : arr) {
if (el != null) {
++count;
}
}
return count - 2;
}
public static String shortest(String words[]) {
if (null == words || words.length < 1) {
return "";
}
String smallest = words[0];
for (int i = 1; i < words.length; i++) {
if (words[i].length() < smallest.length()) {
smallest = words[i];
}
}
return smallest;
}
This is the code in the class that tests it:
public class tests {
public static void main(String[] args) throws Exception {
String[] argz = new String[]{"summary", "csv", "den.csv"};
MovieSummary.main(argz);
}
}
It should give the following output: Total number of records: 87 Shortest title: Hi
But instead it gives the following output: Total number of records: 87 Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "words[i]" is null