I have to make a program where I take a file that contains users order information(the file is from another program I had to make), and then tests it and outputs how many of what it orders. I cant seem to get it to work, its running but then at the end of its ouput has a weird error.

import java.io.*;
import java.util.*;
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Kimberlie
 */
public class OrderSummary {
    public static void main(String[] args)
    {
        try
        {
            BufferedReader read;
            File file;
            String latestLine;
            String line = "Jacket";
            int totalJ = 0;
            int totalP = 0;
            
            
            
            file = new File("order.txt");
            
            read = new BufferedReader(new FileReader(file));
            
            latestLine = read.readLine();
              System.out.println(latestLine);
            while(latestLine != null)
            {
                latestLine = read.readLine();
                if(latestLine.equalsIgnoreCase("Jacket"))
                    totalJ += 1;
                if(latestLine.equals("Pants"));
                    totalP += 1;
                
                    
                System.out.println(totalJ);
            }
            
        }
        catch(IOException e)
        {
            System.out.println("Unable to read file");
        }
    }

}

Recommended Answers

All 3 Replies

this is what it outputs:

Order:
Exception in thread "main" java.lang.NullPointerException
0
at OrderSummary.main(OrderSummary.java:35)
0
0
0
Java Result: 1

just change this

latestLine = read.readLine();
              System.out.println(latestLine);
            while(latestLine != null)
            {
                latestLine = read.readLine();

to

read = new BufferedReader(new FileReader(file));
            
            latestLine = null;
              System.out.println(latestLine);
            while((latestLine = read.readLine()) != null)
            {

It's because you are using the results of readline without first checking what it returned, and readLine returns null at EOF.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.