空指针异常,我不知道为什么

时间:2013-05-10 08:02:44

标签: java xml file-io nullpointerexception

这个问题很复杂,所以我尽力清楚地谈论一切,如果我需要详细说明或者从这篇文章中拿出任何不妥之处,请告诉我。我的程序用于读取XML文件并打印一个包含2个产品的数组,这些产品是从XML文件中恢复的数据,在第一次打印数组后第3次将第3个元素添加到数组中,并在数组打印后删除它第二次。程序告诉用户何时添加或删除第三个元素这意味着所需的输出是

Product list:
code of the first product   name of the first product       price of the first product
code of the second product   name of the second product     price of the second product

XML Tester has been added to the XML document 


Product list:
code of the first product   name of the first product       price of the first product
code of the second product   name of the second product     price of the second product
code of the XML tester       name of the XMl tester         price of the XML tester

XML tester has been deleted from the XML document.


Product list:
code of the first product   name of the first product       price of the first product
code of the second product   name of the second product     price of the second product

然而,在第一次使用新添加的测试仪第二次尝试打印产品时出现Null指针异常错误

这发生在我的代码的第67行,如下所示为了使错误发生的位置更明显并使其更清晰

p.setDescription(description);

我的调试器说的描述目前设置的项目是“Murach的Beginning Java”,我不知道为什么这是一个空指针,因为这个确切的描述在我的程序第一次打印到控制台时工作

这是我的程序看起来像我在调试程序时注意到的事情的注释,以便使这个问题更容易帮助

import java.util.ArrayList;
import java.io.*;
import javax.xml.stream.*;  // StAX API

public class XMLTesterApp
{
    private static String productsFilename = "products.xml";

    public static void main(String[] args)
    {
        **This first part the XML file contains two values and it prints both fine*****
        System.out.println("Products list:");
        ArrayList<Product> products = readProducts();
        printProducts(products);

        *** This part adds a tester line to the print out and this is the point the 
        *** null pointer exception error starts to happen This is used as a test to
        *** make sure my file writer method is working by an instructor and the program
        ***  is supposed to fail here if I am doing something wrong but I can't figure
        ***  out what im doing wrong ************************
        Product p1 = new Product("test", "XML Tester", 77.77);
        products.add(p1);
        writeProducts(products);
        System.out.println("XML Tester has been added to the XML document.\n");


        System.out.println("Products list:");
        products = readProducts();
        printProducts(products);


        products.remove(2);
        writeProducts(products);
        System.out.println("XML Tester has been deleted from the XML document.\n");


        System.out.println("Products list:");
        products = readProducts();
        printProducts(products);

    }

   private static ArrayList<Product> readProducts()
{
    ArrayList<Product> products = new ArrayList<>();
    Product p = null;
    XMLInputFactory inputFactory = XMLInputFactory.newFactory();
    try
    {
        //create a stream reader object
        FileReader fileReader = new FileReader("products.xml");
        XMLStreamReader reader = inputFactory.createXMLStreamReader(fileReader);
        //read XML file
        while (reader.hasNext())
        {
          int eventType = reader.getEventType();
          switch (eventType)
          {
               case  XMLStreamConstants.START_ELEMENT :
                  String elementName = reader.getLocalName();
                  //get the product and its code
                  if (elementName.equals("Product"))
                  {
                     p = new Product();
                     String code = reader.getAttributeValue(0);
                     p.setCode(code);
                  }   
                  // get the product description
                  if (elementName.equals("Description"))
                  {
                     String description = reader.getElementText();
                     ************Error occurs on the line under this note*************
                     p.setDescription(description);

                  }    
                  // get the product price
                  if (elementName.equals("Price")) 
                  {

                      String priceS = reader.getElementText();
                      double price = Double.parseDouble(priceS);
                      **** As I test I removed the set descirption line and then 
                           this line returned the same error that that line
                           did*********************************************
                      p.setPrice(price);
                  }    
                  break;
               case XMLStreamConstants.END_ELEMENT :
                  elementName = reader.getLocalName();
                  if(elementName.equals("Product"))
                  {
                    products.add(p);  
                  }    
                  break; 
              }
         reader.next();
        }    
    }
    catch (IOException | XMLStreamException e)
    {
      System.out.println(e); 
    }    
     return products;
    }

    private static void writeProducts(ArrayList<Product> products)
    {
      XMLOutputFactory outputFactory = XMLOutputFactory.newFactory();
        try
        {
            //create a stream reader object
            FileWriter fileWriter = new FileWriter("products.xml");
            XMLStreamWriter writer = outputFactory.createXMLStreamWriter(fileWriter);
            //write to the XML file
            writer.writeStartDocument("1.0");
            writer.writeStartElement("Products");
            for (Product p : products)
            {
                writer.writeStartElement("Prodcut");
                writer.writeAttribute("Code", p.getCode()) ;
                writer.writeStartElement("Description");  
                writer.writeCharacters(p.getDescription());
                writer.writeEndElement();
                writer.writeStartElement("Price");
                double price = p.getPrice();
                writer.writeCharacters(Double.toString(price));
                writer.writeEndElement();
                writer.writeEndElement();
            }
            writer.writeEndElement();
            writer.flush();
            writer.close();
        }  
        catch (IOException | XMLStreamException e)
        {
           System.out.println("e"); 
        }
    }

    private static void printProducts(ArrayList<Product> products)
    {
        for (Product p : products)
        {
            printProduct(p);
        }
        System.out.println();
    }

    private static void printProduct(Product p)
    {
        String productString =
            StringUtils.padWithSpaces(p.getCode(), 8) +
            StringUtils.padWithSpaces(p.getDescription(), 44) +
            p.getFormattedPrice();

        System.out.println(productString);
    }
}

这是一个课程,我花了几个小时检查我的代码和我的教科书,但无法弄清楚我的代码出错了。

1 个答案:

答案 0 :(得分:2)

看起来原因是:

  writer.writeStartElement("Prodcut");

您正在写出一个元素<Prodcut>,但稍后您尝试处理该元素。您的解析代码永远不会找到<Product>,因此永远不会进入开始语句的部分:

 if (elementName.equals("Product"))

因此您永远不会创建产品对象p。当您尝试在p。

上设置描述时,这会导致空指针异常

您应该能够使用调试器发现这一点。