1

*Note: I have pointers to all created objects. read is initialized in the constructor of the code, as is write. So I'm still confused as to why the exception is occurring. First off, I apologize in advance for the potentially dirty and unrefined coding which is going to follow. I'm not making a career out of this, nor am I studying computer science. I'm trying to make a (relatively) simple program to keep track of some statistics. Everything else works, but when I try to write the gathered stats to a text file, I get a nullpointerexception, at the first read.nextLine() in the readFile() function. The idea is to first read the values already present in the file, add those to the values gathered during the program session, then rewrite the combined values into the file. Below is the complete file:

`import java.util.Scanner; import java.io.*;

public class StatTracker {

private static int numCustomers = 0, BOGO = 0, PERC = 0, BDAY = 0;
private static final String[] couponTypes = {"BOGO","PERC","BDAY"};
private static boolean run = true;
private static final Scanner input = new Scanner(System.in);
private static final String fileName = "Statistics.txt";
private static PrintWriter write;
private static Scanner read;

public StatTracker() throws IOException, FileNotFoundException{

    Scanner read = new Scanner(fileName);
    PrintWriter write = new PrintWriter(fileName);

} //End constructor

public static void main(String[] args) throws IOException {

    StatTracker stat = new StatTracker();
    stat.program(run);

} //End main

public static void program(boolean r) throws IOException{

    while (r){

        getInfo();
        System.out.println("Continue? (y/n): ");
        cont(input.next());

    } //End while

} //End program

public static int[] readFile() throws FileNotFoundException{

    int custTemp = 0, BOGOtemp = 0, PERCtemp = 0, BDAYtemp = 0;

        read.nextLine();
        custTemp = read.nextInt();
        read.nextLine();
        BOGOtemp = read.nextInt();
        read.nextLine();
        PERCtemp = read.nextInt();
        read.nextLine();
        BDAYtemp = read.nextInt();
        read.close();

    int[] currentValues = {custTemp,BOGOtemp,PERCtemp,BDAYtemp};
    return currentValues;

} //End readFile

public static void writeToFile(int[] vals) throws IOException{

    int custTemp = getNumCustomers() + vals[0], BOGOtemp = getBOGO() + vals[1], PERCtemp = getPERC() + vals[2], BDAYtemp = getBDAY() + vals[3];

    write.println("Customers:");
    write.println(custTemp);
    write.println("Buy One Get One Discounts Used:");
    write.println(BOGOtemp);
    write.println("Percent Off Discounts Used:");
    write.println(PERCtemp);
    write.println("Birthday Discounts Used:");
    write.println(BDAYtemp);
    write.close();

} //End writeToFile

//Checks whether to continue running the program
public static void cont(String answer) throws IOException, FileNotFoundException {

    int[] temp = new int[4];

    if (answer.equals("y")) {

        System.out.println("Program still running. Current totals:");
        System.out.println("Customers: " + getNumCustomers());
        System.out.println("BOGO coupons used: " + getBOGO());
        System.out.println("Percent off coupons used: " + getPERC());
        System.out.println("Birthday coupons used: " + getBDAY());

    } else if (answer.equals("n")){

        System.out.println("Writing statistics to file.");
        temp = readFile();
        writeToFile(temp);
        System.out.println("Closing program.");
        switchRun();

    } //End if

} //End cont

public static int getBOGO(){

    return BOGO;

} //End getBOGO

public static int getPERC(){

    return PERC;

} //End getBOGO

public static int getBDAY(){

    return BDAY;

} //End getBOGO

public static int getNumCustomers(){

    return numCustomers;

} //End getNumCustomers

public static void switchRun(){

    if (getRun()){

        run = false;

    } else {

        run = true;

    } //End if

} //End switchRun

public static boolean getRun(){

    return run;

} //End getRun

public static String getCouponType(int index){

    return couponTypes[index];

} //End getCouponType

public static void getInfo(){

    int temp = 0, BOGOtemp = 0, PERCtemp = 0, BDAYtemp = 0;
    boolean checkTemp = false;

    System.out.println("Enter the number of customers:");
    temp = input.nextInt();
    addToNumCustomers(temp);

    while (true){

        System.out.println("If any coupons were used, please enter the number of each in this order:");
        System.out.println(getCouponType(0)+ ", " + getCouponType(1) + ", " + getCouponType(2));
        BOGOtemp = input.nextInt();
        PERCtemp = input.nextInt();
        BDAYtemp = input.nextInt();

        if (checkTooMany(BOGOtemp,PERCtemp,BDAYtemp,temp)){

            System.out.println("More coupons than customers. Please re-enter.");

        } else {

            addToCoupons("BOGO", BOGOtemp);
            addToCoupons("PERC", BOGOtemp);
            addToCoupons("BDAY", BOGOtemp);
            break;

        }//End if

    }
} //End getInfo

public static boolean checkTooMany(int b, int p, int bd, int c){

    //Checks to make sure there aren't more coupons than people.
    if((b + p + bd) > c) {

        return true;

    } else {

        return false;

    } //End if

} //End check

public static void addToNumCustomers(int num){

    numCustomers += num;

} //End addNumCustomers

public static void addBOGO(int num){

    while(true){
      if(num >= 0){

        BOGO += num;
        break;

        } else {

            System.out.println("Invalid number, please re-enter.");
            num = input.nextInt();

        }//End if
    } //End while

} //End addBOGO

public static void addPERC(int num){

    while(true){
      if(num >= 0){

        PERC += num;
        break;

        } else {

            System.out.println("Invalid number, please re-enter.");
            num = input.nextInt();

        }//End if
    } //End while

} //End addPERC

public static void addBDAY(int num){

    while(true){
      if(num >= 0){

        BDAY += num;
        break;

        } else {

            System.out.println("Invalid number, please re-enter.");
            num = input.nextInt();

        } //End if
    } //End while

} //End addBDAY

public static void addToCoupons(String type,int num){

    while(true){
        if (type.equalsIgnoreCase(getCouponType(0))){

            addBOGO(num);
            break;

        } else if (type.equalsIgnoreCase(getCouponType(1))){

            addPERC(num);
            break;

        } else if (type.equalsIgnoreCase(getCouponType(2))){

            addBDAY(num);
            break;

        } else {

            System.out.println("Invalid coupon type, please re-enter.");
            type = input.nextLine();

        } //End if
    } //End while

} //End addToCoupons

} //End StatTracker`

I have tried creating a new file from the program itself (with File new file), creating an empty .txt file, creating one with garbage data on each necessary line, and creating one with a space on each line. Any help you can provide would be greatly appreciated.

  • can you please post your stacktrace – Minato Nov 20 '15 at 10:26
  • I'm sorry, I don't know what stacktrace is – TheJabberwocky Nov 20 '15 at 10:31
  • post wherever you see the error log.. Look into the question that @Vinod marked yours duplicated with – Minato Nov 20 '15 at 10:32
  • `Exception in thread "main" java.lang.NullPointerException at StatTracker.readFile(StatTracker.java:49) at StatTracker.cont(StatTracker.java:94) at StatTracker.program(StatTracker.java:39) at StatTracker.main(StatTracker.java:29)` - @Minato – TheJabberwocky Nov 20 '15 at 10:34
  • where is `write` declared..? – Minato Nov 20 '15 at 10:42
  • At the start of the class: `private static PrintWriter write; private static Scanner read;`, then in the constructor: `public StatTracker() throws IOException, FileNotFoundException{ Scanner read = new Scanner(fileName); PrintWriter write = new PrintWriter(fileName); } //End constructor` – TheJabberwocky Nov 20 '15 at 10:45
  • `PrintWriter write = new PrintWriter(new File("C:/path/to/file.txt"));` you can also provide name inside that function instead of `"C:/path/to/file.txt"` that will simply create the file. and at the end don't forget to write `write.close();` when you are done writing – Minato Nov 20 '15 at 10:48
  • So I can't use PrintWriter(fileName)? I have to specify the directory, or the file will get re-created? Also, thanks for the write.close(), I had forgotten to include that. – TheJabberwocky Nov 20 '15 at 10:51
  • have you called the constructor.. – Minato Nov 20 '15 at 10:51
  • initialize them inside your `main` method not in constructor.. – Minato Nov 20 '15 at 10:54
  • `public StatTracker() throws IOException, FileNotFoundException{ Scanner read = new Scanner(fileName); PrintWriter write = new PrintWriter(fileName); } //End constructor public static void main(String[] args) throws IOException { StatTracker stat = new StatTracker(); stat.program(run); } //End main` Constructor and Main. This is how I currently have it set up. I tried moving the initialize to main, but it gave the same error. – TheJabberwocky Nov 20 '15 at 10:56
  • can you edit your question and post the complete code – Minato Nov 20 '15 at 10:59
  • @Minato Done. I can edit in line numbers if needed. – TheJabberwocky Nov 20 '15 at 11:09
  • @Vinod Madyalkar Could this get unmarked as a duplicate? The question you pointed me to does not seem to be helping, and I have edited the question. – TheJabberwocky Nov 20 '15 at 21:54
  • @TheJabberwocky - Did you try debugging your code?. If you are having a specific issue that might be cause NPE, ask a different question. Reopening this will not do much good :) – TheLostMind Nov 21 '15 at 14:26

0 Answers0