1

I'm tasked, by my professor, to write a program to read a .csv file (778 rows (including header row), 8 columns). I need to: 1. Write a method to receive the name of the file as its argument and then print the number of lines in the file.

public void printNumberOfLinesInFile(String fileName)

  1. Write a method to receive the name of the file as its argument and then print the number of private and non-private colleges.

public void printNumberOfPrivateNonPrivateCollegesInFile(String fileName)

  1. Write a method to receive the name of the file as its argument and then print the private college name with largest out of state tuition.

public void printMostExpensivePrivateCollegeInFile(String fileName)

  1. Write a method to receive the name of the file as its argument and then print the non-private college with largest out of state tuition.

public void printMostExpensiveNonPrivateCollegeInFile(String fileName)

  1. Write a method to receive the name of the file as its argument and then print the number of applications and the number of applicants that are accepted for private and non-private colleges.

public void printNumberOfApplications(String fileName)

  1. Write a method to receive the name of the file as its argument and then print following information for private and non-private colleges.

Average of expenses for books. Average of expenses for room. Average of personal expenses.

public void printAverageOfExpenses(String fileName)

Disclaimer: I do not want anyone to do my homework for me. I need to learn so I can apply my knowledge when I graduate and enter industry. I'm simply asking for a hint or a better way at writing the code.

My code thus far:

    public class Week14 
    {
public String data;



public void printNumberOfLinesInFile(String inFile) throws IOException
{
    int collegeCount = 0;
    FileReader fileRead = new FileReader(inFile);
    BufferedReader bufferRead = new BufferedReader(fileRead);
    while(true)
    {
        String line = bufferRead.readLine();
        if(line == null)
        {
            break;

        }
        collegeCount++;
        //System.out.println(line);
    }
    System.out.println(collegeCount-1 + " Colleges total.");
}
public void printNumberOfPrivateNonPrivateCollegesInFile(String inFile) throws IOException
{
    int privateCount = 0;
    int nonprivateCount = 0;
    int count = 0;
    FileReader fileRead = new FileReader(inFile);
    BufferedReader bufferRead = new BufferedReader(fileRead);
    while((data = bufferRead.readLine())!= null)
    {
        String line = bufferRead.readLine();
        String [] lineItems = line.split(",");
        for(int i = 0; i < line.length(); i++)
        {
            if(lineItems[i].equals("Yes"))
            {
                privateCount++;
            }
        }

        break;
    }
    System.out.println(privateCount+" private Colleges.");
    System.out.println(nonprivateCount+ " non-private Colleges.");
}

public void printMostExpensivePrivateCollegeInFile(String inFile) throws FileNotFoundException, IOException
{
    int mostExpensive = 0;
    int currentExpensive = 0;
    FileReader fileRead = new FileReader(inFile);
    BufferedReader bufferRead = new BufferedReader(fileRead);
    while((data = bufferRead.readLine())!= null)
    {
        String line = bufferRead.readLine();
        if(line.equals("OutstateTuition"))
        {
            System.out.println(line);
        }
        else
        {
            System.out.println(line);
        }
    }



}

public void printMostExpensiveNonPrivateCollegeInFile(String fileName)
{

}

public void printNumberOfApplications(String fileName)
{

}

public void printAverageOfExpenses(String fileName)
{

}
public static void main(String[] args) throws FileNotFoundException, IOException 
{
    File inFile = new File("College.csv");
    FileReader fileReader = new FileReader(inFile);
    BufferedReader buffReader = new BufferedReader(fileReader);
    Week14 w1 = new Week14();
    //w1.printNumberOfLinesInFile("College.csv");
    w1.printNumberOfPrivateNonPrivateCollegesInFile("College.csv");
    //^^^The above line goes into an infinite loop^^^
    //w1.printMostExpensivePrivateCollegeInFile("College.csv");
}

}

The problem is, I'm stuck on trying to count the amount of private and nonprivate colleges. In my method, printNumberOfPrivateNonPrivateCollegesInFile (line 39), I'm running into an exception: java.lang.ArrayIndexOutOfBoundsException: 8

I've asked my professor how I can avoid this, I've looked online and the problem seems to lie with the iterator int 'i'. I'm trying to traverse the array, and 'i' is out of bounds. When I put a '1' in

    if(lineItems[i].equals("Yes"))

for my privateCount, there is an output of 67 from privateCount, (I think it is counting the individual characters for some reason).

My question, what would be the most effective way to traverse the entire .csv file, and to access individual columns so I can count them and output them?

Any help would be greatly appreciated.

edit:

I have changed the while loop:

        while(true)
        {
        String line = bufferRead.readLine();
        String [] lineItems = line.split(",");
        if(line == null)
        {
            break;
        }

        for (String lineItem : lineItems) {
            privateCount++;
        }

    }

Now I can traverse the entire .csv file, but I'm receiving a java.lang.NullPointerException when I try and count.

edit 2: I've redone my while loop again,

    while(true)
    {
        String line = bufferRead.readLine();
        String [] lineItems = line.split(",");

        for (String lineItem : lineItems) {
            if (lineItem.equals("Yes")) {
                privateCount++;
            }
        }
        System.out.println(privateCount);

    }

I'm now counting the right value for privateCount, but there's a NullPointerException at :

    String [] lineItems = line.split(",");

and the loop will not let me put my 'echo' outside of the while-loop without a 'break' statement.

10
  • You're iterating through lineItems but using line.length() as the limit. Why not lineItems.length? Commented May 4, 2015 at 21:44
  • I changed the limit to lineItems.length and am now getting nothing. Commented May 4, 2015 at 21:49
  • I even used a more advanced for-loop: for (String lineItem : lineItems) and am getting nothing. Commented May 4, 2015 at 21:51
  • In fact, I echo'd what was going into the for-loop, and it's only reading the first row of the .csv file, which is the header file. Why isn't it skipping down and traversing the rest of the file? Commented May 4, 2015 at 21:52
  • 2
    Your break; statement is breaking out of your while loop. That is preventing you from processing the entire file. Also, fyi, you are reading lines (bufferRead.readLine()) in two places so you end up only processing every other line. Commented May 4, 2015 at 22:06

3 Answers 3

0

With respect to actual industry-level code, and assuming that assignment did not specifically focus on actual CSV decoding, I would recommend finding and using a library to handle low-level decoding, such as OpenCSV, SuperCSV or CSV-module for Jackson.

This way your code can focus on more interesting part of finding specific values, and not on intricate details like possible escaping and/or quoting of contents.

If the focus is on CSV edge cases this is not the approach to use; but for real production code one hopefully rarely if ever writes the actual low-level decoding part, given the existence of multiple good libraries for the task.

Sign up to request clarification or add additional context in comments.

2 Comments

I appreciate the feedback, I'll take a look at those. I meant that I will have the base-level knowledge to strengthen my understanding when I am into production code. I'm the kind of person who would rather not program his calculator to find a triple integral, I write it out and struggle over it.
Nothing wrong in that, as long as you are aware of existing tools. Just wanted to mention this, because what is often not taught is that you do not have to actually build the tools yourself, even if you should be able to. Learning to understand the "knowing what you don't know" part and such. Good luck!
0
    if(lineItems != null && lineItems.length>0){
      // do your loop 
    }  



 if (lineItem!= null && !lineItem.trim().equals("") && lineItem.equals("Yes")) {
                    privateCount++;
                }

most likely will prevent your null issue

4 Comments

The null is not associated with my if statement. It's on: String [] lineItems = line.split(",");
Use !lineItem.trim().isEmpty() instead of !lineItem.trim().equals("").
in this case check out the array itself if its null.
@AlaaAbuzaghleh Checked the array, had it printed to console. All 778 rows print out in proper format.
0
    public void printNumberOfPrivateNonPrivateCollegesInFile(String inFile) throws IOException
{
    int privateCount = 0;
    int nonprivateCount = 0;

    FileReader fileRead = new FileReader(inFile);
    BufferedReader bufferRead = new BufferedReader(fileRead);
    try
    {
    while(true)
    {
        String line = bufferRead.readLine();
        String [] lineItems = line.split(",");
        //System.out.println(Arrays.toString(lineItems));
        for (String lineItem : lineItems) 
        {
            if (lineItem!= null && !lineItem.trim().isEmpty() && lineItem.equals("No"))
            {
                nonprivateCount++;
            }
            if (lineItem!= null && !lineItem.trim().isEmpty() && lineItem.equals("Yes")) 
            {
            privateCount++;
            }
        }
        //System.out.println(privateCount);

    }
    }
    catch(NullPointerException npe)
    {

    }
    System.out.println(privateCount);
    System.out.println(nonprivateCount);

}

Fixed it. I'm now just catching the exception so it isn't as annoying. Thanks all for the help.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.