0

My code currently compiles and runs. However, the program crashes when the program reaches the line outputFile.println("Package: " + letter); Why does the outputFile.println("Package: " + letter); and other outputFile.println(""); cause the program to crash and not print to the file dataFile? Is dataFile even being created when the try-catch block executes?

import java.util.Scanner;
import java.text.NumberFormat;
import java.util.InputMismatchException;
import java.lang.NullPointerException;
import java.io.*;

public  class Lab5backup
{
    public static void main (String[] args) {
        Scanner keyboard = new Scanner(System.in);
        NumberFormat fmtCurr = NumberFormat.getCurrencyInstance();

        System.out.print("Data file of prior internet usage: ");
        String dataFile = keyboard.nextLine();

        File file = null;           
        Scanner openFile = null;        
        FileWriter writeFile = null;    
        PrintWriter outputFile = null;  

        boolean invalid;
            try {
                openFile = new Scanner(file);
                writeFile = new FileWriter(dataFile, true);
                outputFile = new PrintWriter(writeFile);
                invalid = false;
            }
            catch (FileNotFoundException fnfe) {
                System.out.print("No such file exists; creating it.\n");
                invalid = true;
            }
            catch (NullPointerException npe) {
                System.out.print("No such file exists; creating it.\n");
                invalid = true;
            }
            catch (IOException ioe) {
                invalid = true;
            }

        File inFile = new File(dataFile);

        if (inFile.exists()) {
            averageHours = openFile.nextDouble();
            averagePaid = openFile.nextDouble();
            totalPaid = openFile.nextDouble();
            System.out.println("Usage history: ");
            System.out.println("  Average Hours Used: " + averageHours);
            System.out.println("  Average Paid: " + averagePaid);
            System.out.println("  Total Paid: " + fmtCurr.format(totalPaid));
        }
           //create and validate variables here
           //taken out of example because not important to question

            outputFile.println("Package: " + letter);

            if (openFile.hasNextDouble()) 
                averageHours = ((hours + openFile.nextDouble())/numOfHourInputs++);
            outputFile.println("Hours: " + hours);

            if (openFile.hasNextDouble())
                averagePaid = ((charge + openFile.nextDouble())/numOfCharges++);
            outputFile.println("Charge: " + charge);    
            outputFile.println("Average Hours: " + averageHours);
            outputFile.println("Average Paid: " + averagePaid);
            totalPaid += charge;
            outputFile.println("Total Paid: " + totalPaid);

            openFile.close();
            outputFile.close();

    } //end of main method
}
freebird
  • 11
  • 2
  • Can you provide the error log, with the line which is giving null exception. – nitishagar Feb 14 '15 at 03:53
  • 3
    Your File variable named `file` is null, and you're passing it into a Scanner which would throw a NPE. – initramfs Feb 14 '15 at 03:56
  • @CPUTerminator how do I get rid of the NPE? – freebird Feb 14 '15 at 04:03
  • You would need to pass a valid File object into that variable. If I assume correctly, you're reading from a user-submitted file in which the user specifies via `dataFile`. In that case, change your `file` declaration to `File file = new File(dataFile);` – initramfs Feb 14 '15 at 04:05
  • @CPUTerminator you should write it as an answer, good catch indeed :) – Nir Alfasi Feb 14 '15 at 04:12
  • possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – Oleg Estekhin Feb 14 '15 at 06:12

1 Answers1

2

Your file variable is null when you pass it into the Scanner's constructor on this line:

openFile = new Scanner(file);

This line would throw a NullPointerException as the argument cannot be null in order for the Scanner to be initialized properly.

The scanner openFile in your code seems to reference some other file not directly specified in your code. Given this, I am going to assume you are trying to load the file passed by the user (denoted as dataFile) into the Scanner for processing. To do this, you can utilize the File constructor that takes a String filename/pathname.

Javadoc for new File(String pathname):

Creates a new File instance by converting the given pathname string into an abstract pathname. If the given string is the empty string, then the result is the empty abstract pathname.

Applying this to your code:

Scanner keyboard = new Scanner(System.in);
NumberFormat fmtCurr = NumberFormat.getCurrencyInstance();

double averageHours = 0;
double averagePaid = 0;
double totalPaid = 0;

System.out.print("Data file of prior internet usage: ");
String dataFile = keyboard.nextLine();

File file = new File(dataFile);

// Your code continued below...

Note: You seem to already be doing this for the File variable inFile. In which I suggest you either move that declaration to the top (and pass that into the openFile Scanner) or completely remove it and use your file object in the rest of your code.

initramfs
  • 8,275
  • 2
  • 36
  • 58
  • Do all of the statements in the try block need to be there? (just for future reference) Also, the line that states `outputFile.println("Package: " + letter);` gives me a run time error -- does this mean that the line `outputFile = new PrintWriter(writeFile);` should be outside of the try block? Thank you for your help! @CPUTerminator – freebird Feb 14 '15 at 06:17
  • @freebird Anything that throws a checked exception (e.g. things that throw `IOException`) need to be handled explicitly. This can come from a try-catch structure or a `throws` declaration. There is however no rule to which try-catch structure any method call/object creation should reside in, meaning whilst all the statements which throw `IOException` need to be handled, they can all be in their own separate try-catch. As for the run time error, more information is needed to solve. – initramfs Feb 14 '15 at 06:51