gpt4 book ai didi

java - 调试 NullPointerException

转载 作者:行者123 更新时间:2023-11-30 11:31:55 25 4
gpt4 key购买 nike

试图从 lyndas.com 讲座中找出调试我的代码中发生的空点异常,这些讲座是为 localhost 上激活的链接中的 xml 内容编写的。以下是我的 View 类和 AppMain 类的代码

View .java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import java.net.*;
import java.util.ArrayList;

public class View extends JFrame implements ActionListener {

private static final long serialVersionUID = 12345L;
public ArrayList<String> titles = new ArrayList<String>();
public ArrayList<String> descriptions = new ArrayList<String>();
public ArrayList<String> links = new ArrayList<String>();
public ArrayList<Integer> prices = new ArrayList<Integer>();
public ArrayList<Number> lengths = new ArrayList<Number>();
public JList list;
public JComboBox combo;
public JTextArea textArea = new JTextArea();
public JLabel priceLabel = new JLabel();
public JLabel lengthLabel = new JLabel();
public JScrollPane textScroller;
public View()
{
super("Backpack CA");
setLayout(new FlowLayout());
**loadData("http://localhost:8080/using_drivers/data.jsp");**
}

public void actionPerformed(ActionEvent e) {
}

public void loadData(String xmlURL)
{
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new URL(xmlURL).openStream());
doc.getDocumentElement().normalize();

NodeList nodes = doc.getElementsByTagName("tour");
for (int temp = 0; temp < nodes.getLength(); temp++) {
Node n = nodes.item(temp);
if (n.getNodeType() == Node.ELEMENT_NODE) {
Element e = (Element) n;
titles.add(getTagValue("tourTitle", e));
descriptions.add(getTagValue("description", e));
links.add(getTagValue("link", e).replaceAll("\\s+", ""));
prices.add(Integer.parseInt(getTagValue("price", e)));
lengths.add(Integer.parseInt(getTagValue("length", e)));
**System.out.println(getTagValue("tourTittle", e));**
}
}

} catch (Exception e) {
e.printStackTrace();
}
}

private static String getTagValue(String sTag, Element eElement) {
NodeList nlList;
**nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();**
Node nValue = (Node) nlList.item(0);
return nValue.getNodeValue();
}

}

AppMain.java

import javax.swing.*;

public class AppMain {

public static void main(String[] args) {
**View testView = new View();**
testView.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
testView.setSize(480,320);
testView.setVisible(true);
}
}

最佳答案

eElement.getElementsByTagName(sTag) 或 eElement.getElementsByTagName(sTag).item(0) 返回空值。尝试拆分该指令以找出:

NodeList nl = eElement.getElementsByTagName(sTag);
Node n = nl.item(0);
nlList = n.getChildNodes();

关于java - 调试 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16954681/

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