Domanda

Having a tough time pinpointing an error I'm getting on line 71. I need to read data from a text file, gather the data into some treemaps in order to modify it later in two output files. I have a while loop that modifies the data by placing text in uppercase, and then I split the data into an array for each line, then place that array data inside 3 treemaps. The error is a NullPointerException and when I comment out the line it throws it on a different line, so there's obviously something wrong with my loop in general, I just can't see it. The loop seems to run one time short of going through all the lines, so if the text file has 5 lines, it'll read through 4, give me the correct values, and then throw the error. I've tried modifying the text file's contents, with no avail. I've tried modifying the while loop, no avail either. Any pointers would be greatly appreciated. The text file looks like this:

110001 commercial 500000.00 101

110223 residential 100000.00 104

110020 commercial 1000000.00 107

550020 land 400000.00 105

Here's the error code:

java.lang.NullPointerException
    at realestate.RealEstate.main(RealEstate.java:71)

And here's my code so far:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package realestate;

import java.io.BufferedReader;
import java.io.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import static java.lang.System.out;
import java.nio.file.DirectoryNotEmptyException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * 
 */
public class RealEstate {
    /**
     * @param args the command line arguments
     * @throws java.io.IOException
     */
    public static void main(String[] args) throws IOException {

        Scanner input = new Scanner(System.in);//Prompt user for listings.txt location.
        String listInput = null;
        System.out.print("Please enter the real estate listings.txt file's full path: ");
        listInput = input.next();
        if(listInput.contains("listings.txt") == false) {//Verify input with if else statement.
          System.out.print("\nSorry, the path entered will not work. Please enter the full path to listings.txt: ");
          listInput = input.next();
            if(listInput.contains("listings.txt") == true){//Nested in order to display same message.
                System.out.print("\nThank you, the agentreport.txt file is now available.");
          }
        } else {
            System.out.print("\nThank you, the agentreport.txt file is now available.\n");
        }
    String[][] listArray;  //Initialize array for later data manipulation.
    listArray = new String[10][5];
    listArray = null;
     Path ar = Paths.get("D:\\JAVA\\RealEstate\\agentreport.txt");//Deletes agentreport.txt if it already exists.
     try {
         Files.deleteIfExists(ar);
     } catch (IOException x) {
         System.out.print("\nIO Exception, please try again.");
     }

     //Reads listings.txt, parses information, places data in array, then inside treemaps.
     BufferedReader br = null;
     String[] lineArray = new String[4];
     TreeMap tm1 = new TreeMap();
     TreeMap tm2 = new TreeMap();
     TreeMap tm3 = new TreeMap();
     try {
         br = new BufferedReader(new FileReader(listInput));
            String line = br.readLine();
         while(line != null){//WHERE I"M GETTING ERROR
             line = br.readLine();//Read line.
             line = line.toUpperCase();//Make everything uppercase.
             lineArray = line.split("\\s+");//Place line into new array based on where spaces are.
             tm1.put(lineArray[0], lineArray[1]);//Place array items into treemaps.
             tm2.put(lineArray[0], lineArray[2]);
             tm3.put(lineArray[0], lineArray[3]);
             System.out.print(tm1 + "\n" + tm2 + "\n" + tm3 + "\n");//Test if data is received correctly.
             lineArray = null;//Clear array for next line.
         }
     } catch (NullPointerException e) {
         e.printStackTrace();
     } catch (IOException e) {
         e.printStackTrace();
         System.out.print("\nIO Exception, please try again.");
     }

     try {//File writer, creates file agentreport.txt and starts writing.
       File arFile = new File("D:\\JAVA\\RealEstate\\agentreport.txt");
       FileOutputStream is = new FileOutputStream(arFile);
       OutputStreamWriter osw = new OutputStreamWriter(is);
       Writer w = new BufferedWriter(osw);
       //w.write();//what I need the writer to do
       //w.close();
     } catch (FileNotFoundException e) {
         System.err.println("Problem writing to the file, agentreport.txt");
     }


    } 
}

Thanks in advance!

È stato utile?

Soluzione 2

I'm almost certain you're misreading the line that's triggering the error.

String[] lineArray = new String[4]; // this is not needed, it gets overwritten
...
try {
  br = new BufferedReader(new FileReader(listInput));
  String line = br.readLine();
  while(line != null){
    line = br.readLine();
    line = line.toUpperCase(); // this will NPE
    ...
    lineArray = null; // you don't need this
  }
}

The problem is, you're calling readLine() a second time inside your while-loop, meaning line could now be null. Instead, do this (note the try-with-resources syntax as well):

try(BufferedReader br = new BufferedReader(new FileReader(listInput))) {
  String line = null;
  while((line=br.readLine()) != null){
    String[] lineArray = line.toUpperCase().split("\\s+");
    tm1.put(lineArray[0], lineArray[1]);//Place array items into treemaps.
    tm2.put(lineArray[0], lineArray[2]);
    tm3.put(lineArray[0], lineArray[3]);
    System.out.print(tm1 + "\n" + tm2 + "\n" + tm3 + "\n");//Test if data is received 
  }
}

Altri suggerimenti

change

 br = new BufferedReader(new FileReader(listInput));
        String line = br.readLine();
     while(line != null){//WHERE I"M GETTING ERROR

to

 br = new BufferedReader(new FileReader(listInput));
        String line = null;
     while((line=br.readLine()) != null){//WHERE I"M GETTING ERROR

when you use br.readLine(); inside the loop, it still can get null. so you need to use it before the condition check

p.s.

in your code, you skip the first line. my code will fix this also

You are calling line = br.readLine(); inside the loop and then not checking if it's null or not.

If for example you have 1 line, you will get the NullPointerException

Either follow the suggestion by Dima Goltsman or use the Scanner class like this:

   Scanner scanner = new Scanner(new File(listInput));
   while (scanner.hasNext()) {
      String line = scanner.next();
      //do the rest of your stuff
   }
   scanner.close();
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top