Reading in a File Null Pointer Exception

#1

  • New D.I.C Caput

Reputation: 0

  • View blog
  • Posts: 12
  • Joined: xx-November 15

NullPointerException when reading a text file

Posted twenty Nov 2015 - 03:05 PM

Hello, I apologize in advance for the following code. Information technology is probably riddled with bad programming practices, but I am non studying reckoner science nor is this my career. I'm attempting to make a (relatively) simple programme to keep track of some statistics and save them to a text file. Everything else seems to work, but when the program goes to read the file (using Scanner), I get a nothing pointer exception. I have tried creating this file inside the programme, creating it exterior the program, leaving it bare, filling it with garbage data, and filling information technology with useful data. I have tried moving the scanner and printwriter initializations direct to the main part, also as within the constructor. Hither is the stacktrace:

Exception in thread "main" java.lang.NullPointerException 	at StatTracker.readFile(StatTracker.coffee:l) 	at StatTracker.cont(StatTracker.java:97) 	at StatTracker.plan(StatTracker.java:40) 	at StatTracker.main(StatTracker.coffee:30)            

Below is my program. Whatsoever assist you tin provide would be greatly appreciated.readFile(), writeFile() and cont() are the main functions involved in the error.

import java.util.Scanner; import java.io.*;  public class StatTracker {      private static int numCustomers = 0, BOGO = 0, PERC = 0, BDAY = 0;     private static terminal Cord[] couponTypes = {"BOGO","PERC","BDAY"};     private static boolean run = truthful;     private static final Scanner input = new Scanner(System.in);     individual static final String fileName = "Statistics.txt";     individual static PrintWriter write;     private static Scanner read;          public StatTracker() throws IOException, FileNotFoundException{                                } //End constructor          public static void main(Cord[] args) throws IOException {                  StatTracker stat = new StatTracker();         Scanner read = new Scanner(fileName);         PrintWriter write = new PrintWriter(fileName);         stat.program(run);              } //End principal          public static void program(boolean r) throws IOException{                  while (r){                          getInfo();             Arrangement.out.println("Continue? (y/n): ");             cont(input.next());                      } //Stop while              } //End plan       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;              } //Cease readFile          public static void writeToFile(int[] vals) throws IOException{                  int custTemp = getNumCustomers() + vals[0], BOGOtemp = getBOGO() + vals[1], PERCtemp = getPERC() + vals[two], BDAYtemp = getBDAY() + vals[3];                  write.println("Customers:");         write.println(custTemp);         write.println("Buy One Become 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();              } //Stop writeToFile          //Checks whether to continue running the plan     public static void cont(Cord answer) throws IOException, FileNotFoundException {                  int[] temp = new int[4];                  if (answer.equals("y")) {                          System.out.println("Program still running. Current totals:");             Organization.out.println("Customers: " + getNumCustomers());             Organization.out.println("BOGO coupons used: " + getBOGO());             Organisation.out.println("Percent off coupons used: " + getPERC());             System.out.println("Birthday coupons used: " + getBDAY());                      } else if (answer.equals("due north")){                          Organization.out.println("Writing statistics to file.");             temp = readFile();             writeToFile(temp);             System.out.println("Closing plan.");             switchRun();                      } //Terminate if          } //Finish cont          public static int getBOGO(){                  render BOGO;              } //Finish getBOGO          public static int getPERC(){                  return PERC;              } //End getBOGO          public static int getBDAY(){                  return BDAY;              } //Finish getBOGO          public static int getNumCustomers(){                  render numCustomers;              } //Finish getNumCustomers          public static void switchRun(){                  if (getRun()){                          run = faux;                      } else {                          run = truthful;                      } //End if              } //End switchRun          public static boolean getRun(){                  return run;              } //End getRun          public static Cord getCouponType(int alphabetize){                  return couponTypes[index];              } //End getCouponType          public static void getInfo(){                  int temp = 0, BOGOtemp = 0, PERCtemp = 0, BDAYtemp = 0;         boolean checkTemp = faux;          System.out.println("Enter the number of customers:");         temp = input.nextInt();         addToNumCustomers(temp);                  while (true){                      Organization.out.println("If whatever coupons were used, delight 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);                 suspension;                      }//End if                  }     } //Terminate getInfo             public static boolean checkTooMany(int b, int p, int bd, int c){                  //Checks to make sure there aren't more than coupons than people.         if((b + p + bd) > c) {                          render true;                      } else {                          return imitation;                      } //Terminate if              } //Stop check          public static void addToNumCustomers(int num){                  numCustomers += num;              } //End addNumCustomers          public static void addBOGO(int num){                    while(truthful){           if(num >= 0){                          BOGO += num;             break;                                      } else {                  Organization.out.println("Invalid number, delight re-enter.");                 num = input.nextInt();                          }//Cease if         } //End while                                      } //End addBOGO          public static void addPERC(int num){                  while(truthful){           if(num >= 0){                          PERC += num;             intermission;                                      } else {                  System.out.println("Invalid number, delight re-enter.");                 num = input.nextInt();                          }//Cease 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();                          } //Finish if         } //Stop while              } //End addBDAY          public static void addToCoupons(String blazon,int num){                  while(truthful){             if (blazon.equalsIgnoreCase(getCouponType(0))){                              addBOGO(num);                 break;                          } else if (type.equalsIgnoreCase(getCouponType(1))){                          addPERC(num);                 break;                      } else if (type.equalsIgnoreCase(getCouponType(ii))){                  addBDAY(num);                 break;                      } else {                  System.out.println("Invalid coupon blazon, please re-enter.");                 blazon = input.nextLine();                      } //Cease if         } //End while              } //Finish addToCoupons      } //End StatTracker            

*Note: I forgot to re-create the first few lines. Line 50 in the stacktrace really refers to line 45 in the above code.


Is This A Proficient Question/Topic? 0

  • +

#2 NormR User is offline

Reputation: 870

  • View blog
  • Posts: half-dozen,695
  • Joined: 25-December 13

Re: NullPointerException when reading a text file

Posted 20 November 2015 - 03:07 PM

Quote

Exception in thread "main" java.lang.NullPointerException
at StatTracker.readFile(StatTracker.coffee:l)

In that location is a null value in the plan when line 50 is executed. Find null variable with the null value on line fifty and and so backtrack in the code to see why that variable does not have a valid value.

#three TheJabberwocky User is offline

  • New D.I.C Caput

Reputation: 0

  • View blog
  • Posts: 12
  • Joined: twenty-Nov 15

Re: NullPointerException when reading a text file

Posted xx Nov 2015 - 03:18 PM

View PostNormR, on 20 Nov 2015 - 03:07 PM, said:

Quote

Exception in thread "main" java.lang.NullPointerException
at StatTracker.readFile(StatTracker.java:50)

There is a naught value in the programme when line 50 is executed. Find goose egg variable with the nothing value on line 50 so backtrack in the code to see why that variable does not have a valid value.

Would the "read" scanner exist the null value?

#4 NormR User is offline

Reputation: 870

  • View blog
  • Posts: six,695
  • Joined: 25-December 13

Re: NullPointerException when reading a text file

Posted 20 Nov 2015 - 03:29 PM

If you tin't tell which variable is null, add a impress statement that prints the value in the variable merely earlier the statement where the exception happens.

#v TheJabberwocky User is offline

  • New D.I.C Caput

Reputation: 0

  • View blog
  • Posts: 12
  • Joined: 20-November 15

Re: NullPointerException when reading a text file

Posted 20 November 2015 - 03:45 PM

View PostNormR, on 20 Nov 2015 - 03:29 PM, said:

If you tin can't tell which variable is nada, add together a impress statement that prints the value in the variable but earlier the statement where the exception happens.

Okay, read is coming up as null. Is this a scope problem? Or an outcome with the way I initialized/declared the reader?

#half dozen NormR User is offline

Reputation: 870

  • View blog
  • Posts: 6,695
  • Joined: 25-Dec 13

Re: NullPointerException when reading a text file

Posted 20 November 2015 - 03:52 PM

Quote

Yeah. At that place are two variables with the aforementioned name: read defined at different scopes. The one divers at the class level (outside of any method) needs to exist given a value. You can define a variable at the class level and give information technology a value in a method.

#7 TheJabberwocky User is offline

  • New D.I.C Caput

Reputation: 0

  • View blog
  • Posts: 12
  • Joined: 20-November 15

Re: NullPointerException when reading a text file

Posted 20 November 2015 - 03:55 PM

View PostNormR, on 20 Nov 2015 - 03:29 PM, said:

If you can't tell which variable is nothing, add a print statement that prints the value in the variable simply before the argument where the exception happens.

Okay, I tried something unlike and passed the scanner/printwriter in to the functions which use them. At present I'g getting a unlike mistake:

Exception in thread "principal" java.util.NoSuchElementException 	at java.util.Scanner.throwFor(Scanner.coffee:907) 	at java.util.Scanner.adjacent(Scanner.java:1530) 	at coffee.util.Scanner.nextInt(Scanner.java:2160) 	at java.util.Scanner.nextInt(Scanner.java:2119) 	at StatTracker.readFile(StatTracker.coffee:52) 	at StatTracker.cont(StatTracker.java:98) 	at StatTracker.programme(StatTracker.java:40) 	at StatTracker.main(StatTracker.java:30)            

This is an example of how I changed information technology:

              public static int[] readFile(Scanner reader) throws FileNotFoundException{                  int custTemp = 0, BOGOtemp = 0, PERCtemp = 0, BDAYtemp = 0;         Cord garbage;             Organization.out.println(reader);             garbage = reader.nextLine();             custTemp = reader.nextInt();             garbage = reader.nextLine();             BOGOtemp = reader.nextInt();             garbage = reader.nextLine();             PERCtemp = reader.nextInt();             garbage = reader.nextLine();             BDAYtemp = reader.nextInt();             reader.close();                            int[] currentValues = {custTemp,BOGOtemp,PERCtemp,BDAYtemp};         return currentValues;              } //Terminate readFile            

#8 TheJabberwocky User is offline

  • New D.I.C Head

Reputation: 0

  • View blog
  • Posts: 12
  • Joined: 20-November 15

Re: NullPointerException when reading a text file

Posted 20 November 2015 - 04:00 PM

View PostNormR, on 20 Nov 2015 - 03:52 PM, said:

Quote

Yep. In that location are two variables with the same name: read defined at different scopes. The one defined at the course level (outside of any method) needs to be given a value. You can define a variable at the course level and give information technology a value in a method.

Okay, I had missed the part where I used Scanner and PrintWriter again redundantly. Thanks very much. The declaration/initialization is at present every bit follows:

private static PrintWriter write;     private static Scanner read;            

Inside the class. Then, inside main:

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

This eliminated the nullpointer error, but now this error comes upwardly:

Exception in thread "main" java.util.NoSuchElementException 	at java.util.Scanner.throwFor(Scanner.java:907) 	at coffee.util.Scanner.next(Scanner.coffee:1530) 	at java.util.Scanner.nextInt(Scanner.java:2160) 	at java.util.Scanner.nextInt(Scanner.java:2119) 	at StatTracker.readFile(StatTracker.java:52) 	at StatTracker.cont(StatTracker.java:98) 	at StatTracker.plan(StatTracker.java:twoscore) 	at StatTracker.main(StatTracker.java:xxx)            

#ix NormR User is offline

Reputation: 870

  • View blog
  • Posts: 6,695
  • Joined: 25-December 13

Re: NullPointerException when reading a text file

Posted twenty November 2015 - 04:35 PM

Quote

xception in thread "master" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at coffee.util.Scanner.side by side(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at StatTracker.readFile(StatTracker.coffee:52)

The statement at line 52 calls the nextInt() method when there is non whatsoever information to be read (NoSuchElement).
Make sure in that location is something to read before calling any read method. The Scanner grade has methods to test if at that place is data available. The method names brainstorm with has.

#10 TheJabberwocky User is offline

  • New D.I.C Head

Reputation: 0

  • View blog
  • Posts: 12
  • Joined: 20-Nov xv

Re: NullPointerException when reading a text file

Posted 20 November 2015 - 04:45 PM

View PostNormR, on twenty Nov 2015 - 04:35 PM, said:

Quote

xception in thread "principal" java.util.NoSuchElementException
at coffee.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.adjacent(Scanner.java:1530)
at coffee.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.coffee:2119)
at StatTracker.readFile(StatTracker.java:52)

The statement at line 52 calls the nextInt() method when there is non any data to exist read (NoSuchElement).
Brand sure in that location is something to read before calling any read method. The Scanner form has methods to test if at that place is data available. The method names begin with has.

I filled the txt file with zeroes for 9 lines, i figured that would be plenty. Or is in that location some special parsing I need to do in guild to be able to read the data?

#11 TheJabberwocky User is offline

  • New D.I.C Head

Reputation: 0

  • View blog
  • Posts: 12
  • Joined: 20-November 15

Re: NullPointerException when reading a text file

Posted 20 November 2015 - 04:53 PM

View PostNormR, on 20 Nov 2015 - 04:35 PM, said:

Quote

xception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.coffee:907)
at java.util.Scanner.side by side(Scanner.java:1530)
at coffee.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.coffee:2119)
at StatTracker.readFile(StatTracker.coffee:52)

The statement at line 52 calls the nextInt() method when there is not any data to be read (NoSuchElement).
Make sure there is something to read earlier calling any read method. The Scanner grade has methods to test if in that location is data available. The method names begin with has.

Non sure if this will be helpful, only I tried deleting the file and using the plan to create it. Now it creates a text file with a unlike number on each line. Information technology still throws the nosuchelement exception.

#12 NormR User is offline

Reputation: 870

  • View blog
  • Posts: 6,695
  • Joined: 25-December 13

Re: NullPointerException when reading a text file

Posted xx Nov 2015 - 04:54 PM

Add together some print statements, one after each nextInt() method call, that prints out what was just read so you can see the progress the plan makes reading the file.

Also print out the value of garbage.

This postal service has been edited by NormR: xx Nov 2015 - 04:55 PM

#13 TheJabberwocky User is offline

  • New D.I.C Head

Reputation: 0

  • View blog
  • Posts: 12
  • Joined: 20-November 15

Re: NullPointerException when reading a text file

Posted twenty November 2015 - 04:59 PM

View PostNormR, on twenty November 2015 - 04:54 PM, said:

Add some impress statements, one after each nextInt() method telephone call, that prints out what was but read so you can see the progress the program makes reading the file.

As well impress out the value of garbage.

The commencement line of garbage that prints out is the name of the file, Statistics.txt. The programme ever fails on the first read.nextInt() call, so cipher but the proper noun prints

#14 NormR User is offline

Reputation: 870

  • View blog
  • Posts: 6,695
  • Joined: 25-December xiii

Re: NullPointerException when reading a text file

Posted twenty November 2015 - 05:03 PM

Quote

The first line of garbage that prints out is the proper name of the file, Statistics.txt.

Look at the API md for the Scanner class to see how to utilize it to read a file. What is the argument for the constructor?
Likewise await at what the grade does when a String is passed to the constructor.

#15 TheJabberwocky User is offline

  • New D.I.C Head

Reputation: 0

  • View blog
  • Posts: 12
  • Joined: twenty-Nov xv

Re: NullPointerException when reading a text file

Posted xx November 2015 - 06:05 PM

View PostNormR, on 20 November 2015 - 05:03 PM, said:

Quote

The starting time line of garbage that prints out is the name of the file, Statistics.txt.

Await at the API doc for the Scanner form to meet how to utilise it to read a file. What is the statement for the constructor?
Also look at what the course does when a String is passed to the constructor.

Alright, I got it to terminate crashing at to the lowest degree. However, it still isn't reading any data. Saving the read lines to an assortment and so press them produces the name of the file, then null for 7 lines. This is the new code:

public static int[] readFile() throws FileNotFoundException{                  int custTemp = 0, BOGOtemp = 0, PERCtemp = 0, BDAYtemp = 0;         String[] data = new String[viii];          int i = 0;         while(read.hasNext()){                          data[i] = read.adjacent();             i++;                      } //Terminate while         read.close();         for(i = 0; i < 8; i++){                          System.out.println(data[i]);                                  } //Finish for                            //custTemp = Integer.parseInt(data[1]);        // BOGOtemp = Integer.parseInt(information[three]);        // PERCtemp = Integer.parseInt(data[5]);         //BDAYtemp = Integer.parseInt(data[seven]);                  int[] currentValues = {custTemp,BOGOtemp,PERCtemp,BDAYtemp};         render currentValues;              } //End readFile            

I'chiliad still not sure why it reads no values. I looked into the constructor, but can't decipher what it ways by charset, etc.

View PostNormR, on 20 November 2015 - 05:03 PM, said:

Quote

The first line of garbage that prints out is the proper name of the file, Statistics.txt.

Look at the API dr. for the Scanner class to meet how to use information technology to read a file. What is the argument for the constructor?
Too look at what the grade does when a String is passed to the constructor.

If there is a better or simpler style to beginning read the values present in the file, then add them to values gained during programme runtime, then write the new values into the file, I would profoundly honey to know what it is.

huiepropis.blogspot.com

Source: https://www.dreamincode.net/forums/topic/384831-nullpointerexception-when-reading-a-text-file/

0 Response to "Reading in a File Null Pointer Exception"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel