gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 07:02:21 27 4
gpt4 key购买 nike

这个问题很复杂,所以我会尽力清楚地谈论所有内容,如果我需要详细说明任何内容或从这篇文章中删除任何不相关的内容,请告诉我。我的程序用于读取 XML 文件并打印一个包含 2 个产品的数组,这些产品是从 XML 文件中恢复的数据,在数组第一次打印后将第三个元素添加到数组中 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

但是,第一次尝试使用新添加的测试器第二次打印产品时出现空指针异常错误

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

p.setDescription(description);

我的调试器说此时设置的描述是“Murach's 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);
}
}

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

最佳答案

看起来原因是:

  writer.writeStartElement("Prodcut");

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

 if (elementName.equals("Product"))

所以你永远不会创建一个产品对象p。当您尝试在 p 上设置描述时,这会导致空指针异常。

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

关于java - 空指针异常,我不知道为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16477665/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com