Java NullPointerException javax.xml.transform

Java NullPointerException javax.xml.transform,java,xml,nullpointerexception,Java,Xml,Nullpointerexception,我编写了一个简单的XMLPhoneBook程序,从用户(从输入控制台)获取输入,如firstname、lastname和电话号码,并将其保存到名为“PhoneBook.XML”的XML文件中。该程序还检查现有的xml文件,如果该文件已经存在,则更新该文件,或者创建一个新文件。我编写的没有错误处理类的代码的第一个版本是成功的 当我试图用错误处理类更新代码时,我开始从javax.xml.transform获取NullPointerException。我已经在下面发布了我的代码的两个版本供您理解 没有

我编写了一个简单的XMLPhoneBook程序,从用户(从输入控制台)获取输入,如firstname、lastname和电话号码,并将其保存到名为“PhoneBook.XML”的XML文件中。该程序还检查现有的xml文件,如果该文件已经存在,则更新该文件,或者创建一个新文件。我编写的没有错误处理类的代码的第一个版本是成功的

当我试图用错误处理类更新代码时,我开始从javax.xml.transform获取NullPointerException。我已经在下面发布了我的代码的两个版本供您理解

没有错误处理的主类XMLPhoneBook。

    /**
     *
     * @author Sanjayan Ravi
     */
    /**
     *
     * Class XMLPhoneBook is the Main Class that controls getContactInfo function and storeContactInfo.
     */
    public class XMLPhoneBook 
    {
        GetContactInformation gci;
        StoreContactInformation sci;

        XMLPhoneBook()
        {
            gci = new GetContactInformation();
        }
        /**
        *
        * getContactInfo function triggers the functions getFirstName, getLastName, getPhoneNumber of the GetContactInformation class.
        */
        void getContactInfo(){
            gci.getFirstName();
            gci.getLastName();
            gci.getPhoneNumber();
        }
        /**
        *
        * The variables FName, LName, PhoneNumber of the class GetContactInformation contains the user entered data, these values are passed to the class StoreContactInformation for creating/updating an XML file with user data.
        */
        void storeContactInfo(){
            sci = new StoreContactInformation(gci.FName,gci.LName,gci.PhoneNumber);
        }
        public static void main(String[] args) 
        {
            XMLPhoneBook pb = new XMLPhoneBook();
            pb.getContactInfo();
            pb.storeContactInfo();
        }

    }
    /**
    *
    * Class GetContactInformation is responsible for getting inputs from the user such as First Name, Last Name and Phone Number. 
    * The variables FName(String), LName(String), PhoneNumber(long) are used for containing the user data during run time.
    * The Variable reader(Scanner) is used for getting inputs from the user via the console.
    */
    import java.util.Scanner;

    public class GetContactInformation {
        String FName;
        String LName;
        long PhoneNumber;
        Scanner reader;

        GetContactInformation(){
            FName=null;
            LName=null;
            PhoneNumber=0;
        }
        /**
         *
         * The function getFirstName prompts the user for this first name and gets the inputs from the console.
         * Then the value for the first name is passed to the function setFirstName.
         */
        void getFirstName(){
            System.out.println("Enter Your FirstName = ");
            reader = new Scanner(System.in);
            setFirstName(reader.nextLine());
        }
         /**
         *
         * The function getLastName prompts the user for this last name and gets the inputs from the console.
         * Then the value for the last name is passed to the function setLastName.
         */
        void getLastName(){
            System.out.println("Enter Your LastName = ");
            reader = new Scanner(System.in);
            setLastName(reader.nextLine());
        }
         /**
         *
         * The function getPhoneNumber prompts the user for this phone number and gets the inputs from the console.
         * Then the value for the phone number is passed to the function setPhoneNumber.
         */
        void getPhoneNumber(){
            try{
                System.out.println("Enter Your PhoneNumber = ");
                reader = new Scanner(System.in);  
                setPhoneNumber(Long.parseUnsignedLong(reader.nextLine()));
            }catch(java.lang.NumberFormatException e){

            }

        }
        /**
         *
         * The function setFirstName assigns the value it receives to the variable FName.
         */
        String setFirstName(String FN){
           return  FName=FN;
        }
        /**
         *
         * The function setLastName assigns the value it receives to the variable LName.
         */
        String setLastName(String LN){
            return  LName=LN;
        }
         /**
         *
         * The function setPhoneNumber assigns the value it receives to the variable PhoneNumber.
         */
        long setPhoneNumber(long PN){
            return  PhoneNumber=PN;
        }
    }
    /**
     *
     * The StoreContactInformation is responsible for storing the user data such as first name, last name and phone number into an XML file called PhoneBook.xml.
     * The StoreContactInformation first checks if the XML file already exist then if the file exist it simply updates the file or else creates a new XML file with the provided user data.
     *
     */
    import java.io.File;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerException;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import javax.xml.transform.OutputKeys;

    import org.w3c.dom.Attr;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;

    import org.xml.sax.SAXException;
    import java.io.IOException;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;

    public class StoreContactInformation {

        File f;
        String filePathString ;
        DocumentBuilderFactory docFactory ;
        DocumentBuilder docBuilder ;
        Document doc;
        TransformerFactory transformerFactory;
        Transformer transformer;
        DOMSource source;
        StreamResult result;
        String FirstName;
        String LastName;
        long PhoneNumber;

        StoreContactInformation(String fn, String ln, long pn){

            filePathString="PhoneBook.xml"; //File Path is the current working directory. 
            f = new File(filePathString);
            FirstName=fn;
            LastName=ln;
            PhoneNumber=pn;
            docFactory = DocumentBuilderFactory.newInstance();
            try {
                docBuilder = docFactory.newDocumentBuilder();
                }
            catch (ParserConfigurationException pce) 
                {
                    pce.printStackTrace();
                } 
            transformerFactory = TransformerFactory.newInstance();
            try 
                {
                    transformer = transformerFactory.newTransformer();
                }
            catch (TransformerException tfe)
                {
                    tfe.printStackTrace();
                }
            // check if the XML file exist already !        
            if(f.exists() && !f.isDirectory()) {
                //if exist
                UpdateXMLFile();
                WriteToXMLFile(); 
            }else{
                //if do not exist
                CreateXMLFile(); 
                WriteToXMLFile();
            } 

        }
        /**
        *
        * The function CreateXMLFile creates a new XML file if one doesn't exist already. 
        * The first set of data stored in the XML file is given the unique id="1".
        * The root element of the XML file is "ContactInformation" which contains child nodes "Contact" with there unique ids.
        * The element "contact further contains child nodes "FirstName","LastName" and "PhoneNumber".
        */
        void CreateXMLFile(){

            doc = docBuilder.newDocument();
            Element rootElement = doc.createElement("ContactInformation");
            doc.appendChild(rootElement);
            Element contact = doc.createElement("Contact");
            rootElement.appendChild(contact);
            Attr attr = doc.createAttribute("id");
            attr.setValue("1");
            contact.setAttributeNode(attr);
            Element firstname = doc.createElement("FirstName");
            firstname.appendChild(doc.createTextNode(FirstName));
            contact.appendChild(firstname);
            Element lastname = doc.createElement("LastName");
            lastname.appendChild(doc.createTextNode(LastName));
            contact.appendChild(lastname);
            Element PN = doc.createElement("PhoneNumber");
            PN.appendChild(doc.createTextNode(java.lang.Long.toString(PhoneNumber)));
            contact.appendChild(PN);

        }
        /**
        *
        * The function WriteToXMLFile is responsible for writing the data into output XML file "PhoneBook.xml".
        * WriteToXMLFile also formats the data to be written into pretty print way with INDENT spaces and line breaks etc.
        */
        void WriteToXMLFile(){
            try 
                {
                transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
                source = new DOMSource(doc);
                result = new StreamResult(new File(filePathString));
                transformer.transform(source, result);
                System.out.println("Contact Saved !");
                }
            catch (TransformerException tfe) 
                {
                    tfe.printStackTrace();

                }
        }
        /**
        *
        * The function UpdateXMLFile updates the existing XML file with the new user data.
        * The new set of user data gets a unique id for the element "Contact" which is calculated and generated by UpdateXMLFile.
        * 
        */
        void UpdateXMLFile(){
            try
            {
                doc = docBuilder.parse(filePathString);
            }catch(SAXException sae){

            }catch (IOException ioe) {
            ioe.printStackTrace();
        } 
            int AttrValue=1;
            Node ContactInfo = doc.getFirstChild();
            NodeList NumberChildNodes = ContactInfo.getChildNodes();
            for(int i=0;i<NumberChildNodes.getLength();i++)
                {            
                    Node n = NumberChildNodes.item(i);
                    if ("Contact".equals(n.getNodeName())) 
                        {
                            AttrValue+=1;
                        }     
                }            
        Element contact = doc.createElement("Contact");
        ContactInfo.appendChild(contact);
            Attr attr = doc.createAttribute("id");
            attr.setValue(Integer.toString(AttrValue));
            contact.setAttributeNode(attr);
            Element firstname = doc.createElement("FirstName");
            firstname.appendChild(doc.createTextNode(FirstName));
            contact.appendChild(firstname);
            Element lastname = doc.createElement("LastName");
            lastname.appendChild(doc.createTextNode(LastName));
            contact.appendChild(lastname);
            Element PN = doc.createElement("PhoneNumber");
            PN.appendChild(doc.createTextNode(java.lang.Long.toString(PhoneNumber)));
            contact.appendChild(PN);

        }
    }
无需错误处理即可获取联系人信息。

    /**
     *
     * @author Sanjayan Ravi
     */
    /**
     *
     * Class XMLPhoneBook is the Main Class that controls getContactInfo function and storeContactInfo.
     */
    public class XMLPhoneBook 
    {
        GetContactInformation gci;
        StoreContactInformation sci;

        XMLPhoneBook()
        {
            gci = new GetContactInformation();
        }
        /**
        *
        * getContactInfo function triggers the functions getFirstName, getLastName, getPhoneNumber of the GetContactInformation class.
        */
        void getContactInfo(){
            gci.getFirstName();
            gci.getLastName();
            gci.getPhoneNumber();
        }
        /**
        *
        * The variables FName, LName, PhoneNumber of the class GetContactInformation contains the user entered data, these values are passed to the class StoreContactInformation for creating/updating an XML file with user data.
        */
        void storeContactInfo(){
            sci = new StoreContactInformation(gci.FName,gci.LName,gci.PhoneNumber);
        }
        public static void main(String[] args) 
        {
            XMLPhoneBook pb = new XMLPhoneBook();
            pb.getContactInfo();
            pb.storeContactInfo();
        }

    }
    /**
    *
    * Class GetContactInformation is responsible for getting inputs from the user such as First Name, Last Name and Phone Number. 
    * The variables FName(String), LName(String), PhoneNumber(long) are used for containing the user data during run time.
    * The Variable reader(Scanner) is used for getting inputs from the user via the console.
    */
    import java.util.Scanner;

    public class GetContactInformation {
        String FName;
        String LName;
        long PhoneNumber;
        Scanner reader;

        GetContactInformation(){
            FName=null;
            LName=null;
            PhoneNumber=0;
        }
        /**
         *
         * The function getFirstName prompts the user for this first name and gets the inputs from the console.
         * Then the value for the first name is passed to the function setFirstName.
         */
        void getFirstName(){
            System.out.println("Enter Your FirstName = ");
            reader = new Scanner(System.in);
            setFirstName(reader.nextLine());
        }
         /**
         *
         * The function getLastName prompts the user for this last name and gets the inputs from the console.
         * Then the value for the last name is passed to the function setLastName.
         */
        void getLastName(){
            System.out.println("Enter Your LastName = ");
            reader = new Scanner(System.in);
            setLastName(reader.nextLine());
        }
         /**
         *
         * The function getPhoneNumber prompts the user for this phone number and gets the inputs from the console.
         * Then the value for the phone number is passed to the function setPhoneNumber.
         */
        void getPhoneNumber(){
            try{
                System.out.println("Enter Your PhoneNumber = ");
                reader = new Scanner(System.in);  
                setPhoneNumber(Long.parseUnsignedLong(reader.nextLine()));
            }catch(java.lang.NumberFormatException e){

            }

        }
        /**
         *
         * The function setFirstName assigns the value it receives to the variable FName.
         */
        String setFirstName(String FN){
           return  FName=FN;
        }
        /**
         *
         * The function setLastName assigns the value it receives to the variable LName.
         */
        String setLastName(String LN){
            return  LName=LN;
        }
         /**
         *
         * The function setPhoneNumber assigns the value it receives to the variable PhoneNumber.
         */
        long setPhoneNumber(long PN){
            return  PhoneNumber=PN;
        }
    }
    /**
     *
     * The StoreContactInformation is responsible for storing the user data such as first name, last name and phone number into an XML file called PhoneBook.xml.
     * The StoreContactInformation first checks if the XML file already exist then if the file exist it simply updates the file or else creates a new XML file with the provided user data.
     *
     */
    import java.io.File;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerException;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import javax.xml.transform.OutputKeys;

    import org.w3c.dom.Attr;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;

    import org.xml.sax.SAXException;
    import java.io.IOException;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;

    public class StoreContactInformation {

        File f;
        String filePathString ;
        DocumentBuilderFactory docFactory ;
        DocumentBuilder docBuilder ;
        Document doc;
        TransformerFactory transformerFactory;
        Transformer transformer;
        DOMSource source;
        StreamResult result;
        String FirstName;
        String LastName;
        long PhoneNumber;

        StoreContactInformation(String fn, String ln, long pn){

            filePathString="PhoneBook.xml"; //File Path is the current working directory. 
            f = new File(filePathString);
            FirstName=fn;
            LastName=ln;
            PhoneNumber=pn;
            docFactory = DocumentBuilderFactory.newInstance();
            try {
                docBuilder = docFactory.newDocumentBuilder();
                }
            catch (ParserConfigurationException pce) 
                {
                    pce.printStackTrace();
                } 
            transformerFactory = TransformerFactory.newInstance();
            try 
                {
                    transformer = transformerFactory.newTransformer();
                }
            catch (TransformerException tfe)
                {
                    tfe.printStackTrace();
                }
            // check if the XML file exist already !        
            if(f.exists() && !f.isDirectory()) {
                //if exist
                UpdateXMLFile();
                WriteToXMLFile(); 
            }else{
                //if do not exist
                CreateXMLFile(); 
                WriteToXMLFile();
            } 

        }
        /**
        *
        * The function CreateXMLFile creates a new XML file if one doesn't exist already. 
        * The first set of data stored in the XML file is given the unique id="1".
        * The root element of the XML file is "ContactInformation" which contains child nodes "Contact" with there unique ids.
        * The element "contact further contains child nodes "FirstName","LastName" and "PhoneNumber".
        */
        void CreateXMLFile(){

            doc = docBuilder.newDocument();
            Element rootElement = doc.createElement("ContactInformation");
            doc.appendChild(rootElement);
            Element contact = doc.createElement("Contact");
            rootElement.appendChild(contact);
            Attr attr = doc.createAttribute("id");
            attr.setValue("1");
            contact.setAttributeNode(attr);
            Element firstname = doc.createElement("FirstName");
            firstname.appendChild(doc.createTextNode(FirstName));
            contact.appendChild(firstname);
            Element lastname = doc.createElement("LastName");
            lastname.appendChild(doc.createTextNode(LastName));
            contact.appendChild(lastname);
            Element PN = doc.createElement("PhoneNumber");
            PN.appendChild(doc.createTextNode(java.lang.Long.toString(PhoneNumber)));
            contact.appendChild(PN);

        }
        /**
        *
        * The function WriteToXMLFile is responsible for writing the data into output XML file "PhoneBook.xml".
        * WriteToXMLFile also formats the data to be written into pretty print way with INDENT spaces and line breaks etc.
        */
        void WriteToXMLFile(){
            try 
                {
                transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
                source = new DOMSource(doc);
                result = new StreamResult(new File(filePathString));
                transformer.transform(source, result);
                System.out.println("Contact Saved !");
                }
            catch (TransformerException tfe) 
                {
                    tfe.printStackTrace();

                }
        }
        /**
        *
        * The function UpdateXMLFile updates the existing XML file with the new user data.
        * The new set of user data gets a unique id for the element "Contact" which is calculated and generated by UpdateXMLFile.
        * 
        */
        void UpdateXMLFile(){
            try
            {
                doc = docBuilder.parse(filePathString);
            }catch(SAXException sae){

            }catch (IOException ioe) {
            ioe.printStackTrace();
        } 
            int AttrValue=1;
            Node ContactInfo = doc.getFirstChild();
            NodeList NumberChildNodes = ContactInfo.getChildNodes();
            for(int i=0;i<NumberChildNodes.getLength();i++)
                {            
                    Node n = NumberChildNodes.item(i);
                    if ("Contact".equals(n.getNodeName())) 
                        {
                            AttrValue+=1;
                        }     
                }            
        Element contact = doc.createElement("Contact");
        ContactInfo.appendChild(contact);
            Attr attr = doc.createAttribute("id");
            attr.setValue(Integer.toString(AttrValue));
            contact.setAttributeNode(attr);
            Element firstname = doc.createElement("FirstName");
            firstname.appendChild(doc.createTextNode(FirstName));
            contact.appendChild(firstname);
            Element lastname = doc.createElement("LastName");
            lastname.appendChild(doc.createTextNode(LastName));
            contact.appendChild(lastname);
            Element PN = doc.createElement("PhoneNumber");
            PN.appendChild(doc.createTextNode(java.lang.Long.toString(PhoneNumber)));
            contact.appendChild(PN);

        }
    }
最后一节课存储联系人信息,无错误处理。

    /**
     *
     * @author Sanjayan Ravi
     */
    /**
     *
     * Class XMLPhoneBook is the Main Class that controls getContactInfo function and storeContactInfo.
     */
    public class XMLPhoneBook 
    {
        GetContactInformation gci;
        StoreContactInformation sci;

        XMLPhoneBook()
        {
            gci = new GetContactInformation();
        }
        /**
        *
        * getContactInfo function triggers the functions getFirstName, getLastName, getPhoneNumber of the GetContactInformation class.
        */
        void getContactInfo(){
            gci.getFirstName();
            gci.getLastName();
            gci.getPhoneNumber();
        }
        /**
        *
        * The variables FName, LName, PhoneNumber of the class GetContactInformation contains the user entered data, these values are passed to the class StoreContactInformation for creating/updating an XML file with user data.
        */
        void storeContactInfo(){
            sci = new StoreContactInformation(gci.FName,gci.LName,gci.PhoneNumber);
        }
        public static void main(String[] args) 
        {
            XMLPhoneBook pb = new XMLPhoneBook();
            pb.getContactInfo();
            pb.storeContactInfo();
        }

    }
    /**
    *
    * Class GetContactInformation is responsible for getting inputs from the user such as First Name, Last Name and Phone Number. 
    * The variables FName(String), LName(String), PhoneNumber(long) are used for containing the user data during run time.
    * The Variable reader(Scanner) is used for getting inputs from the user via the console.
    */
    import java.util.Scanner;

    public class GetContactInformation {
        String FName;
        String LName;
        long PhoneNumber;
        Scanner reader;

        GetContactInformation(){
            FName=null;
            LName=null;
            PhoneNumber=0;
        }
        /**
         *
         * The function getFirstName prompts the user for this first name and gets the inputs from the console.
         * Then the value for the first name is passed to the function setFirstName.
         */
        void getFirstName(){
            System.out.println("Enter Your FirstName = ");
            reader = new Scanner(System.in);
            setFirstName(reader.nextLine());
        }
         /**
         *
         * The function getLastName prompts the user for this last name and gets the inputs from the console.
         * Then the value for the last name is passed to the function setLastName.
         */
        void getLastName(){
            System.out.println("Enter Your LastName = ");
            reader = new Scanner(System.in);
            setLastName(reader.nextLine());
        }
         /**
         *
         * The function getPhoneNumber prompts the user for this phone number and gets the inputs from the console.
         * Then the value for the phone number is passed to the function setPhoneNumber.
         */
        void getPhoneNumber(){
            try{
                System.out.println("Enter Your PhoneNumber = ");
                reader = new Scanner(System.in);  
                setPhoneNumber(Long.parseUnsignedLong(reader.nextLine()));
            }catch(java.lang.NumberFormatException e){

            }

        }
        /**
         *
         * The function setFirstName assigns the value it receives to the variable FName.
         */
        String setFirstName(String FN){
           return  FName=FN;
        }
        /**
         *
         * The function setLastName assigns the value it receives to the variable LName.
         */
        String setLastName(String LN){
            return  LName=LN;
        }
         /**
         *
         * The function setPhoneNumber assigns the value it receives to the variable PhoneNumber.
         */
        long setPhoneNumber(long PN){
            return  PhoneNumber=PN;
        }
    }
    /**
     *
     * The StoreContactInformation is responsible for storing the user data such as first name, last name and phone number into an XML file called PhoneBook.xml.
     * The StoreContactInformation first checks if the XML file already exist then if the file exist it simply updates the file or else creates a new XML file with the provided user data.
     *
     */
    import java.io.File;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerException;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import javax.xml.transform.OutputKeys;

    import org.w3c.dom.Attr;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;

    import org.xml.sax.SAXException;
    import java.io.IOException;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;

    public class StoreContactInformation {

        File f;
        String filePathString ;
        DocumentBuilderFactory docFactory ;
        DocumentBuilder docBuilder ;
        Document doc;
        TransformerFactory transformerFactory;
        Transformer transformer;
        DOMSource source;
        StreamResult result;
        String FirstName;
        String LastName;
        long PhoneNumber;

        StoreContactInformation(String fn, String ln, long pn){

            filePathString="PhoneBook.xml"; //File Path is the current working directory. 
            f = new File(filePathString);
            FirstName=fn;
            LastName=ln;
            PhoneNumber=pn;
            docFactory = DocumentBuilderFactory.newInstance();
            try {
                docBuilder = docFactory.newDocumentBuilder();
                }
            catch (ParserConfigurationException pce) 
                {
                    pce.printStackTrace();
                } 
            transformerFactory = TransformerFactory.newInstance();
            try 
                {
                    transformer = transformerFactory.newTransformer();
                }
            catch (TransformerException tfe)
                {
                    tfe.printStackTrace();
                }
            // check if the XML file exist already !        
            if(f.exists() && !f.isDirectory()) {
                //if exist
                UpdateXMLFile();
                WriteToXMLFile(); 
            }else{
                //if do not exist
                CreateXMLFile(); 
                WriteToXMLFile();
            } 

        }
        /**
        *
        * The function CreateXMLFile creates a new XML file if one doesn't exist already. 
        * The first set of data stored in the XML file is given the unique id="1".
        * The root element of the XML file is "ContactInformation" which contains child nodes "Contact" with there unique ids.
        * The element "contact further contains child nodes "FirstName","LastName" and "PhoneNumber".
        */
        void CreateXMLFile(){

            doc = docBuilder.newDocument();
            Element rootElement = doc.createElement("ContactInformation");
            doc.appendChild(rootElement);
            Element contact = doc.createElement("Contact");
            rootElement.appendChild(contact);
            Attr attr = doc.createAttribute("id");
            attr.setValue("1");
            contact.setAttributeNode(attr);
            Element firstname = doc.createElement("FirstName");
            firstname.appendChild(doc.createTextNode(FirstName));
            contact.appendChild(firstname);
            Element lastname = doc.createElement("LastName");
            lastname.appendChild(doc.createTextNode(LastName));
            contact.appendChild(lastname);
            Element PN = doc.createElement("PhoneNumber");
            PN.appendChild(doc.createTextNode(java.lang.Long.toString(PhoneNumber)));
            contact.appendChild(PN);

        }
        /**
        *
        * The function WriteToXMLFile is responsible for writing the data into output XML file "PhoneBook.xml".
        * WriteToXMLFile also formats the data to be written into pretty print way with INDENT spaces and line breaks etc.
        */
        void WriteToXMLFile(){
            try 
                {
                transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
                source = new DOMSource(doc);
                result = new StreamResult(new File(filePathString));
                transformer.transform(source, result);
                System.out.println("Contact Saved !");
                }
            catch (TransformerException tfe) 
                {
                    tfe.printStackTrace();

                }
        }
        /**
        *
        * The function UpdateXMLFile updates the existing XML file with the new user data.
        * The new set of user data gets a unique id for the element "Contact" which is calculated and generated by UpdateXMLFile.
        * 
        */
        void UpdateXMLFile(){
            try
            {
                doc = docBuilder.parse(filePathString);
            }catch(SAXException sae){

            }catch (IOException ioe) {
            ioe.printStackTrace();
        } 
            int AttrValue=1;
            Node ContactInfo = doc.getFirstChild();
            NodeList NumberChildNodes = ContactInfo.getChildNodes();
            for(int i=0;i<NumberChildNodes.getLength();i++)
                {            
                    Node n = NumberChildNodes.item(i);
                    if ("Contact".equals(n.getNodeName())) 
                        {
                            AttrValue+=1;
                        }     
                }            
        Element contact = doc.createElement("Contact");
        ContactInfo.appendChild(contact);
            Attr attr = doc.createAttribute("id");
            attr.setValue(Integer.toString(AttrValue));
            contact.setAttributeNode(attr);
            Element firstname = doc.createElement("FirstName");
            firstname.appendChild(doc.createTextNode(FirstName));
            contact.appendChild(firstname);
            Element lastname = doc.createElement("LastName");
            lastname.appendChild(doc.createTextNode(LastName));
            contact.appendChild(lastname);
            Element PN = doc.createElement("PhoneNumber");
            PN.appendChild(doc.createTextNode(java.lang.Long.toString(PhoneNumber)));
            contact.appendChild(PN);

        }
    }
当我试图用错误处理类更新上述代码时,我的问题开始了,如下所示

获取的主类XMLPhoneBook是异常:

C:\Users\xxxxxx\Documents\Java\xml>java XMLPhoneBook
Enter Your FirstName =
XXXXXX
Enter Your LastName =
YYYYYY
Enter Your PhoneNumber =
789634569863
Contact Saved !
    /**
     *
     * @author Sanjayan Ravi
     */
    package xmlphonebook;
    /**
     *
     * Class XMLPhoneBook is the Main Class that controls getContactInfo function and storeContactInfo.
     */
    public class XMLPhoneBook 
    {
        GetContactInformation gci;
        StoreContactInformation sci;


        XMLPhoneBook()
        {
            gci = new GetContactInformation();

        }
        /**
        *
        * getContactInfo function triggers the functions getFirstName, getLastName, getPhoneNumber of the GetContactInformation class.
        */
        void getContactInfo()throws Exception {        
            gci.getFirstName();
            gci.getLastName();
            gci.getPhoneNumber();
        }
        /**
        *
        * The variables FName, LName, PhoneNumber of the class GetContactInformation contains the user entered data, these values are passed to the class StoreContactInformation for creating/updating an XML file with user data.
        */
        void storeContactInfo()throws Exception{             
            sci = new StoreContactInformation(gci.FName,gci.LName,gci.PhoneNumber);               
        }

        public static void main(String[] args) 
        {
            XMLPhoneBook pb = new XMLPhoneBook();
            try{
            pb.getContactInfo();
            pb.storeContactInfo();
            }catch(Exception e){
                ErrorHandler er = new ErrorHandler(e);
            }
        }

    }
    package xmlphonebook;
    /**
    *
    * Class GetContactInformation is responsible for getting inputs from the user such as First Name, Last Name and Phone Number. 
    * The variables FName(String), LName(String), PhoneNumber(long) are used for containing the user data during run time.
    * The Variable reader(Scanner) is used for getting inputs from the user via the console.
    */
    import java.util.Scanner;

    public class GetContactInformation {
        String FName;
        String LName;
        long PhoneNumber;
        Scanner reader;

        GetContactInformation(){
            FName=null;
            LName=null;
            PhoneNumber=0;
        }
        /**
         *
         * The function getFirstName prompts the user for this first name and gets the inputs from the console.
         * Then the value for the first name is passed to the function setFirstName.
         */
        void getFirstName()throws Exception{
            System.out.println("Enter Your FirstName = ");
            reader = new Scanner(System.in);
            setFirstName(reader.nextLine());
        }
         /**
         *
         * The function getLastName prompts the user for this last name and gets the inputs from the console.
         * Then the value for the last name is passed to the function setLastName.
         */
        void getLastName()throws Exception{
            System.out.println("Enter Your LastName = ");
            reader = new Scanner(System.in);
            setLastName(reader.nextLine());
        }
         /**
         *
         * The function getPhoneNumber prompts the user for this phone number and gets the inputs from the console.
         * Then the value for the phone number is passed to the function setPhoneNumber.
         */
        void getPhoneNumber()throws Exception{

            System.out.println("Enter Your PhoneNumber = ");
            reader = new Scanner(System.in);  
            setPhoneNumber(Long.parseUnsignedLong(reader.nextLine()));

        }
        /**
         *
         * The function setFirstName assigns the value it receives to the variable FName.
         */
        String setFirstName(String FN)throws Exception{
           return  FName=FN;
        }
        /**
         *
         * The function setLastName assigns the value it receives to the variable LName.
         */
        String setLastName(String LN)throws Exception{
            return  LName=LN;
        }
         /**
         *
         * The function setPhoneNumber assigns the value it receives to the variable PhoneNumber.
         */
        long setPhoneNumber(long PN)throws Exception{
            return  PhoneNumber=PN;
        }
    }
    package xmlphonebook;
    /**
     *
     * The StoreContactInformation is responsible for storing the user data such as first name, last name and phone number into an XML file called PhoneBook.xml.
     * The StoreContactInformation first checks if the XML file already exist then if the file exist it simply updates the file or else creates a new XML file with the provided user data.
     *
     */
    import java.io.File;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import javax.xml.transform.OutputKeys;
    import javax.xml.transform.TransformerException;

    import org.w3c.dom.Attr;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;

    import java.util.Scanner;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;


    public class StoreContactInformation {

        File f;
        String filePathString ;
        DocumentBuilderFactory docFactory ;
        DocumentBuilder docBuilder ;
        Document doc;
        TransformerFactory transformerFactory;
        Transformer transformer;
        DOMSource source;
        StreamResult result;
        String FirstName;
        String LastName;
        long PhoneNumber;
        int choice;
        Scanner reader;
        OutputKeys OutputKeys;

        StoreContactInformation(String fn, String ln, long pn) throws Exception {

            filePathString="PhoneBook.xml"; //File Path is the current working directory. 
            f = new File(filePathString);
            FirstName=fn;
            LastName=ln;
            PhoneNumber=pn;
            docFactory = DocumentBuilderFactory.newInstance();
            docBuilder = docFactory.newDocumentBuilder();
            transformerFactory = TransformerFactory.newInstance();

            // check if the XML file exist already !        
            if(f.exists() && !f.isDirectory()) {
                //if exist
                UpdateXMLFile();
                WriteToXMLFile(); 
            }else{
                //if do not exist
                CreateXMLFile(); 
                WriteToXMLFile();
            } 


        }
        /**
        *
        * The function CreateXMLFile creates a new XML file if one doesn't exist already. 
        * The first set of data stored in the XML file is given the unique id="1".
        * The root element of the XML file is "ContactInformation" which contains child nodes "Contact" with there unique ids.
        * The element "contact further contains child nodes "FirstName","LastName" and "PhoneNumber".
        */
        void CreateXMLFile(){

            doc = docBuilder.newDocument();
            Element rootElement = doc.createElement("ContactInformation");
            doc.appendChild(rootElement);
            Element contact = doc.createElement("Contact");
            rootElement.appendChild(contact);
            Attr attr = doc.createAttribute("id");
            attr.setValue("1");
            contact.setAttributeNode(attr);
            Element firstname = doc.createElement("FirstName");
            firstname.appendChild(doc.createTextNode(FirstName));
            contact.appendChild(firstname);
            Element lastname = doc.createElement("LastName");
            lastname.appendChild(doc.createTextNode(LastName));
            contact.appendChild(lastname);
            Element PN = doc.createElement("PhoneNumber");
            PN.appendChild(doc.createTextNode(java.lang.Long.toString(PhoneNumber)));
            contact.appendChild(PN);

        }
        /**
        *
        * The function WriteToXMLFile is responsible for writing the data into output XML file "PhoneBook.xml".
        * WriteToXMLFile also formats the data to be written into pretty print way with INDENT spaces and line breaks etc.
        */
        void WriteToXMLFile() throws Exception{

            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
            source = new DOMSource(doc);
            result = new StreamResult(new File(filePathString));
            transformer.transform(source, result);
            System.out.println("Contact Saved !");

        }
        /**
        *
        * The function UpdateXMLFile updates the existing XML file with the new user data.
        * The new set of user data gets a unique id for the element "Contact" which is calculated and generated by UpdateXMLFile.
        * 
        */
        void UpdateXMLFile() throws Exception{

            doc = docBuilder.parse(filePathString);
            int AttrValue=1;
            Node ContactInfo = doc.getFirstChild();
            NodeList NumberChildNodes = ContactInfo.getChildNodes();
            for(int i=0;i<NumberChildNodes.getLength();i++)
                {            
                    Node n = NumberChildNodes.item(i);
                    if ("Contact".equals(n.getNodeName())) 
                        {
                            AttrValue+=1;
                        }     
                }     
            Element contact = doc.createElement("Contact");
            ContactInfo.appendChild(contact);
            Attr attr = doc.createAttribute("id");
            attr.setValue(Integer.toString(AttrValue));
            contact.setAttributeNode(attr);
            Element firstname = doc.createElement("FirstName");
            firstname.appendChild(doc.createTextNode(FirstName));
            contact.appendChild(firstname);
            Element lastname = doc.createElement("LastName");
            lastname.appendChild(doc.createTextNode(LastName));
            contact.appendChild(lastname);
            Element PN = doc.createElement("PhoneNumber");
            PN.appendChild(doc.createTextNode(java.lang.Long.toString(PhoneNumber)));
            contact.appendChild(PN);

        }


    }
Enter Your FirstName = 
xxxxxxxx
Enter Your LastName = 
yyyyyyyy
Enter Your PhoneNumber = 
7896456123693
 void WriteToXMLFile() throws Exception{

        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        source = new DOMSource(doc);
        result = new StreamResult(new File(filePathString));
        transformer.transform(source, result);
        System.out.println("Contact Saved !");

    }
Class GetContactInformation:

C:\Users\xxxxxx\Documents\Java\xml>java XMLPhoneBook
Enter Your FirstName =
XXXXXX
Enter Your LastName =
YYYYYY
Enter Your PhoneNumber =
789634569863
Contact Saved !
    /**
     *
     * @author Sanjayan Ravi
     */
    package xmlphonebook;
    /**
     *
     * Class XMLPhoneBook is the Main Class that controls getContactInfo function and storeContactInfo.
     */
    public class XMLPhoneBook 
    {
        GetContactInformation gci;
        StoreContactInformation sci;


        XMLPhoneBook()
        {
            gci = new GetContactInformation();

        }
        /**
        *
        * getContactInfo function triggers the functions getFirstName, getLastName, getPhoneNumber of the GetContactInformation class.
        */
        void getContactInfo()throws Exception {        
            gci.getFirstName();
            gci.getLastName();
            gci.getPhoneNumber();
        }
        /**
        *
        * The variables FName, LName, PhoneNumber of the class GetContactInformation contains the user entered data, these values are passed to the class StoreContactInformation for creating/updating an XML file with user data.
        */
        void storeContactInfo()throws Exception{             
            sci = new StoreContactInformation(gci.FName,gci.LName,gci.PhoneNumber);               
        }

        public static void main(String[] args) 
        {
            XMLPhoneBook pb = new XMLPhoneBook();
            try{
            pb.getContactInfo();
            pb.storeContactInfo();
            }catch(Exception e){
                ErrorHandler er = new ErrorHandler(e);
            }
        }

    }
    package xmlphonebook;
    /**
    *
    * Class GetContactInformation is responsible for getting inputs from the user such as First Name, Last Name and Phone Number. 
    * The variables FName(String), LName(String), PhoneNumber(long) are used for containing the user data during run time.
    * The Variable reader(Scanner) is used for getting inputs from the user via the console.
    */
    import java.util.Scanner;

    public class GetContactInformation {
        String FName;
        String LName;
        long PhoneNumber;
        Scanner reader;

        GetContactInformation(){
            FName=null;
            LName=null;
            PhoneNumber=0;
        }
        /**
         *
         * The function getFirstName prompts the user for this first name and gets the inputs from the console.
         * Then the value for the first name is passed to the function setFirstName.
         */
        void getFirstName()throws Exception{
            System.out.println("Enter Your FirstName = ");
            reader = new Scanner(System.in);
            setFirstName(reader.nextLine());
        }
         /**
         *
         * The function getLastName prompts the user for this last name and gets the inputs from the console.
         * Then the value for the last name is passed to the function setLastName.
         */
        void getLastName()throws Exception{
            System.out.println("Enter Your LastName = ");
            reader = new Scanner(System.in);
            setLastName(reader.nextLine());
        }
         /**
         *
         * The function getPhoneNumber prompts the user for this phone number and gets the inputs from the console.
         * Then the value for the phone number is passed to the function setPhoneNumber.
         */
        void getPhoneNumber()throws Exception{

            System.out.println("Enter Your PhoneNumber = ");
            reader = new Scanner(System.in);  
            setPhoneNumber(Long.parseUnsignedLong(reader.nextLine()));

        }
        /**
         *
         * The function setFirstName assigns the value it receives to the variable FName.
         */
        String setFirstName(String FN)throws Exception{
           return  FName=FN;
        }
        /**
         *
         * The function setLastName assigns the value it receives to the variable LName.
         */
        String setLastName(String LN)throws Exception{
            return  LName=LN;
        }
         /**
         *
         * The function setPhoneNumber assigns the value it receives to the variable PhoneNumber.
         */
        long setPhoneNumber(long PN)throws Exception{
            return  PhoneNumber=PN;
        }
    }
    package xmlphonebook;
    /**
     *
     * The StoreContactInformation is responsible for storing the user data such as first name, last name and phone number into an XML file called PhoneBook.xml.
     * The StoreContactInformation first checks if the XML file already exist then if the file exist it simply updates the file or else creates a new XML file with the provided user data.
     *
     */
    import java.io.File;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import javax.xml.transform.OutputKeys;
    import javax.xml.transform.TransformerException;

    import org.w3c.dom.Attr;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;

    import java.util.Scanner;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;


    public class StoreContactInformation {

        File f;
        String filePathString ;
        DocumentBuilderFactory docFactory ;
        DocumentBuilder docBuilder ;
        Document doc;
        TransformerFactory transformerFactory;
        Transformer transformer;
        DOMSource source;
        StreamResult result;
        String FirstName;
        String LastName;
        long PhoneNumber;
        int choice;
        Scanner reader;
        OutputKeys OutputKeys;

        StoreContactInformation(String fn, String ln, long pn) throws Exception {

            filePathString="PhoneBook.xml"; //File Path is the current working directory. 
            f = new File(filePathString);
            FirstName=fn;
            LastName=ln;
            PhoneNumber=pn;
            docFactory = DocumentBuilderFactory.newInstance();
            docBuilder = docFactory.newDocumentBuilder();
            transformerFactory = TransformerFactory.newInstance();

            // check if the XML file exist already !        
            if(f.exists() && !f.isDirectory()) {
                //if exist
                UpdateXMLFile();
                WriteToXMLFile(); 
            }else{
                //if do not exist
                CreateXMLFile(); 
                WriteToXMLFile();
            } 


        }
        /**
        *
        * The function CreateXMLFile creates a new XML file if one doesn't exist already. 
        * The first set of data stored in the XML file is given the unique id="1".
        * The root element of the XML file is "ContactInformation" which contains child nodes "Contact" with there unique ids.
        * The element "contact further contains child nodes "FirstName","LastName" and "PhoneNumber".
        */
        void CreateXMLFile(){

            doc = docBuilder.newDocument();
            Element rootElement = doc.createElement("ContactInformation");
            doc.appendChild(rootElement);
            Element contact = doc.createElement("Contact");
            rootElement.appendChild(contact);
            Attr attr = doc.createAttribute("id");
            attr.setValue("1");
            contact.setAttributeNode(attr);
            Element firstname = doc.createElement("FirstName");
            firstname.appendChild(doc.createTextNode(FirstName));
            contact.appendChild(firstname);
            Element lastname = doc.createElement("LastName");
            lastname.appendChild(doc.createTextNode(LastName));
            contact.appendChild(lastname);
            Element PN = doc.createElement("PhoneNumber");
            PN.appendChild(doc.createTextNode(java.lang.Long.toString(PhoneNumber)));
            contact.appendChild(PN);

        }
        /**
        *
        * The function WriteToXMLFile is responsible for writing the data into output XML file "PhoneBook.xml".
        * WriteToXMLFile also formats the data to be written into pretty print way with INDENT spaces and line breaks etc.
        */
        void WriteToXMLFile() throws Exception{

            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
            source = new DOMSource(doc);
            result = new StreamResult(new File(filePathString));
            transformer.transform(source, result);
            System.out.println("Contact Saved !");

        }
        /**
        *
        * The function UpdateXMLFile updates the existing XML file with the new user data.
        * The new set of user data gets a unique id for the element "Contact" which is calculated and generated by UpdateXMLFile.
        * 
        */
        void UpdateXMLFile() throws Exception{

            doc = docBuilder.parse(filePathString);
            int AttrValue=1;
            Node ContactInfo = doc.getFirstChild();
            NodeList NumberChildNodes = ContactInfo.getChildNodes();
            for(int i=0;i<NumberChildNodes.getLength();i++)
                {            
                    Node n = NumberChildNodes.item(i);
                    if ("Contact".equals(n.getNodeName())) 
                        {
                            AttrValue+=1;
                        }     
                }     
            Element contact = doc.createElement("Contact");
            ContactInfo.appendChild(contact);
            Attr attr = doc.createAttribute("id");
            attr.setValue(Integer.toString(AttrValue));
            contact.setAttributeNode(attr);
            Element firstname = doc.createElement("FirstName");
            firstname.appendChild(doc.createTextNode(FirstName));
            contact.appendChild(firstname);
            Element lastname = doc.createElement("LastName");
            lastname.appendChild(doc.createTextNode(LastName));
            contact.appendChild(lastname);
            Element PN = doc.createElement("PhoneNumber");
            PN.appendChild(doc.createTextNode(java.lang.Long.toString(PhoneNumber)));
            contact.appendChild(PN);

        }


    }
Enter Your FirstName = 
xxxxxxxx
Enter Your LastName = 
yyyyyyyy
Enter Your PhoneNumber = 
7896456123693
 void WriteToXMLFile() throws Exception{

        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        source = new DOMSource(doc);
        result = new StreamResult(new File(filePathString));
        transformer.transform(source, result);
        System.out.println("Contact Saved !");

    }
班级商店联系人信息:

C:\Users\xxxxxx\Documents\Java\xml>java XMLPhoneBook
Enter Your FirstName =
XXXXXX
Enter Your LastName =
YYYYYY
Enter Your PhoneNumber =
789634569863
Contact Saved !
    /**
     *
     * @author Sanjayan Ravi
     */
    package xmlphonebook;
    /**
     *
     * Class XMLPhoneBook is the Main Class that controls getContactInfo function and storeContactInfo.
     */
    public class XMLPhoneBook 
    {
        GetContactInformation gci;
        StoreContactInformation sci;


        XMLPhoneBook()
        {
            gci = new GetContactInformation();

        }
        /**
        *
        * getContactInfo function triggers the functions getFirstName, getLastName, getPhoneNumber of the GetContactInformation class.
        */
        void getContactInfo()throws Exception {        
            gci.getFirstName();
            gci.getLastName();
            gci.getPhoneNumber();
        }
        /**
        *
        * The variables FName, LName, PhoneNumber of the class GetContactInformation contains the user entered data, these values are passed to the class StoreContactInformation for creating/updating an XML file with user data.
        */
        void storeContactInfo()throws Exception{             
            sci = new StoreContactInformation(gci.FName,gci.LName,gci.PhoneNumber);               
        }

        public static void main(String[] args) 
        {
            XMLPhoneBook pb = new XMLPhoneBook();
            try{
            pb.getContactInfo();
            pb.storeContactInfo();
            }catch(Exception e){
                ErrorHandler er = new ErrorHandler(e);
            }
        }

    }
    package xmlphonebook;
    /**
    *
    * Class GetContactInformation is responsible for getting inputs from the user such as First Name, Last Name and Phone Number. 
    * The variables FName(String), LName(String), PhoneNumber(long) are used for containing the user data during run time.
    * The Variable reader(Scanner) is used for getting inputs from the user via the console.
    */
    import java.util.Scanner;

    public class GetContactInformation {
        String FName;
        String LName;
        long PhoneNumber;
        Scanner reader;

        GetContactInformation(){
            FName=null;
            LName=null;
            PhoneNumber=0;
        }
        /**
         *
         * The function getFirstName prompts the user for this first name and gets the inputs from the console.
         * Then the value for the first name is passed to the function setFirstName.
         */
        void getFirstName()throws Exception{
            System.out.println("Enter Your FirstName = ");
            reader = new Scanner(System.in);
            setFirstName(reader.nextLine());
        }
         /**
         *
         * The function getLastName prompts the user for this last name and gets the inputs from the console.
         * Then the value for the last name is passed to the function setLastName.
         */
        void getLastName()throws Exception{
            System.out.println("Enter Your LastName = ");
            reader = new Scanner(System.in);
            setLastName(reader.nextLine());
        }
         /**
         *
         * The function getPhoneNumber prompts the user for this phone number and gets the inputs from the console.
         * Then the value for the phone number is passed to the function setPhoneNumber.
         */
        void getPhoneNumber()throws Exception{

            System.out.println("Enter Your PhoneNumber = ");
            reader = new Scanner(System.in);  
            setPhoneNumber(Long.parseUnsignedLong(reader.nextLine()));

        }
        /**
         *
         * The function setFirstName assigns the value it receives to the variable FName.
         */
        String setFirstName(String FN)throws Exception{
           return  FName=FN;
        }
        /**
         *
         * The function setLastName assigns the value it receives to the variable LName.
         */
        String setLastName(String LN)throws Exception{
            return  LName=LN;
        }
         /**
         *
         * The function setPhoneNumber assigns the value it receives to the variable PhoneNumber.
         */
        long setPhoneNumber(long PN)throws Exception{
            return  PhoneNumber=PN;
        }
    }
    package xmlphonebook;
    /**
     *
     * The StoreContactInformation is responsible for storing the user data such as first name, last name and phone number into an XML file called PhoneBook.xml.
     * The StoreContactInformation first checks if the XML file already exist then if the file exist it simply updates the file or else creates a new XML file with the provided user data.
     *
     */
    import java.io.File;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import javax.xml.transform.OutputKeys;
    import javax.xml.transform.TransformerException;

    import org.w3c.dom.Attr;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;

    import java.util.Scanner;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;


    public class StoreContactInformation {

        File f;
        String filePathString ;
        DocumentBuilderFactory docFactory ;
        DocumentBuilder docBuilder ;
        Document doc;
        TransformerFactory transformerFactory;
        Transformer transformer;
        DOMSource source;
        StreamResult result;
        String FirstName;
        String LastName;
        long PhoneNumber;
        int choice;
        Scanner reader;
        OutputKeys OutputKeys;

        StoreContactInformation(String fn, String ln, long pn) throws Exception {

            filePathString="PhoneBook.xml"; //File Path is the current working directory. 
            f = new File(filePathString);
            FirstName=fn;
            LastName=ln;
            PhoneNumber=pn;
            docFactory = DocumentBuilderFactory.newInstance();
            docBuilder = docFactory.newDocumentBuilder();
            transformerFactory = TransformerFactory.newInstance();

            // check if the XML file exist already !        
            if(f.exists() && !f.isDirectory()) {
                //if exist
                UpdateXMLFile();
                WriteToXMLFile(); 
            }else{
                //if do not exist
                CreateXMLFile(); 
                WriteToXMLFile();
            } 


        }
        /**
        *
        * The function CreateXMLFile creates a new XML file if one doesn't exist already. 
        * The first set of data stored in the XML file is given the unique id="1".
        * The root element of the XML file is "ContactInformation" which contains child nodes "Contact" with there unique ids.
        * The element "contact further contains child nodes "FirstName","LastName" and "PhoneNumber".
        */
        void CreateXMLFile(){

            doc = docBuilder.newDocument();
            Element rootElement = doc.createElement("ContactInformation");
            doc.appendChild(rootElement);
            Element contact = doc.createElement("Contact");
            rootElement.appendChild(contact);
            Attr attr = doc.createAttribute("id");
            attr.setValue("1");
            contact.setAttributeNode(attr);
            Element firstname = doc.createElement("FirstName");
            firstname.appendChild(doc.createTextNode(FirstName));
            contact.appendChild(firstname);
            Element lastname = doc.createElement("LastName");
            lastname.appendChild(doc.createTextNode(LastName));
            contact.appendChild(lastname);
            Element PN = doc.createElement("PhoneNumber");
            PN.appendChild(doc.createTextNode(java.lang.Long.toString(PhoneNumber)));
            contact.appendChild(PN);

        }
        /**
        *
        * The function WriteToXMLFile is responsible for writing the data into output XML file "PhoneBook.xml".
        * WriteToXMLFile also formats the data to be written into pretty print way with INDENT spaces and line breaks etc.
        */
        void WriteToXMLFile() throws Exception{

            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
            source = new DOMSource(doc);
            result = new StreamResult(new File(filePathString));
            transformer.transform(source, result);
            System.out.println("Contact Saved !");

        }
        /**
        *
        * The function UpdateXMLFile updates the existing XML file with the new user data.
        * The new set of user data gets a unique id for the element "Contact" which is calculated and generated by UpdateXMLFile.
        * 
        */
        void UpdateXMLFile() throws Exception{

            doc = docBuilder.parse(filePathString);
            int AttrValue=1;
            Node ContactInfo = doc.getFirstChild();
            NodeList NumberChildNodes = ContactInfo.getChildNodes();
            for(int i=0;i<NumberChildNodes.getLength();i++)
                {            
                    Node n = NumberChildNodes.item(i);
                    if ("Contact".equals(n.getNodeName())) 
                        {
                            AttrValue+=1;
                        }     
                }     
            Element contact = doc.createElement("Contact");
            ContactInfo.appendChild(contact);
            Attr attr = doc.createAttribute("id");
            attr.setValue(Integer.toString(AttrValue));
            contact.setAttributeNode(attr);
            Element firstname = doc.createElement("FirstName");
            firstname.appendChild(doc.createTextNode(FirstName));
            contact.appendChild(firstname);
            Element lastname = doc.createElement("LastName");
            lastname.appendChild(doc.createTextNode(LastName));
            contact.appendChild(lastname);
            Element PN = doc.createElement("PhoneNumber");
            PN.appendChild(doc.createTextNode(java.lang.Long.toString(PhoneNumber)));
            contact.appendChild(PN);

        }


    }
Enter Your FirstName = 
xxxxxxxx
Enter Your LastName = 
yyyyyyyy
Enter Your PhoneNumber = 
7896456123693
 void WriteToXMLFile() throws Exception{

        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        source = new DOMSource(doc);
        result = new StreamResult(new File(filePathString));
        transformer.transform(source, result);
        System.out.println("Contact Saved !");

    }
输出:

C:\Users\xxxxxx\Documents\Java\xml>java XMLPhoneBook
Enter Your FirstName =
XXXXXX
Enter Your LastName =
YYYYYY
Enter Your PhoneNumber =
789634569863
Contact Saved !
    /**
     *
     * @author Sanjayan Ravi
     */
    package xmlphonebook;
    /**
     *
     * Class XMLPhoneBook is the Main Class that controls getContactInfo function and storeContactInfo.
     */
    public class XMLPhoneBook 
    {
        GetContactInformation gci;
        StoreContactInformation sci;


        XMLPhoneBook()
        {
            gci = new GetContactInformation();

        }
        /**
        *
        * getContactInfo function triggers the functions getFirstName, getLastName, getPhoneNumber of the GetContactInformation class.
        */
        void getContactInfo()throws Exception {        
            gci.getFirstName();
            gci.getLastName();
            gci.getPhoneNumber();
        }
        /**
        *
        * The variables FName, LName, PhoneNumber of the class GetContactInformation contains the user entered data, these values are passed to the class StoreContactInformation for creating/updating an XML file with user data.
        */
        void storeContactInfo()throws Exception{             
            sci = new StoreContactInformation(gci.FName,gci.LName,gci.PhoneNumber);               
        }

        public static void main(String[] args) 
        {
            XMLPhoneBook pb = new XMLPhoneBook();
            try{
            pb.getContactInfo();
            pb.storeContactInfo();
            }catch(Exception e){
                ErrorHandler er = new ErrorHandler(e);
            }
        }

    }
    package xmlphonebook;
    /**
    *
    * Class GetContactInformation is responsible for getting inputs from the user such as First Name, Last Name and Phone Number. 
    * The variables FName(String), LName(String), PhoneNumber(long) are used for containing the user data during run time.
    * The Variable reader(Scanner) is used for getting inputs from the user via the console.
    */
    import java.util.Scanner;

    public class GetContactInformation {
        String FName;
        String LName;
        long PhoneNumber;
        Scanner reader;

        GetContactInformation(){
            FName=null;
            LName=null;
            PhoneNumber=0;
        }
        /**
         *
         * The function getFirstName prompts the user for this first name and gets the inputs from the console.
         * Then the value for the first name is passed to the function setFirstName.
         */
        void getFirstName()throws Exception{
            System.out.println("Enter Your FirstName = ");
            reader = new Scanner(System.in);
            setFirstName(reader.nextLine());
        }
         /**
         *
         * The function getLastName prompts the user for this last name and gets the inputs from the console.
         * Then the value for the last name is passed to the function setLastName.
         */
        void getLastName()throws Exception{
            System.out.println("Enter Your LastName = ");
            reader = new Scanner(System.in);
            setLastName(reader.nextLine());
        }
         /**
         *
         * The function getPhoneNumber prompts the user for this phone number and gets the inputs from the console.
         * Then the value for the phone number is passed to the function setPhoneNumber.
         */
        void getPhoneNumber()throws Exception{

            System.out.println("Enter Your PhoneNumber = ");
            reader = new Scanner(System.in);  
            setPhoneNumber(Long.parseUnsignedLong(reader.nextLine()));

        }
        /**
         *
         * The function setFirstName assigns the value it receives to the variable FName.
         */
        String setFirstName(String FN)throws Exception{
           return  FName=FN;
        }
        /**
         *
         * The function setLastName assigns the value it receives to the variable LName.
         */
        String setLastName(String LN)throws Exception{
            return  LName=LN;
        }
         /**
         *
         * The function setPhoneNumber assigns the value it receives to the variable PhoneNumber.
         */
        long setPhoneNumber(long PN)throws Exception{
            return  PhoneNumber=PN;
        }
    }
    package xmlphonebook;
    /**
     *
     * The StoreContactInformation is responsible for storing the user data such as first name, last name and phone number into an XML file called PhoneBook.xml.
     * The StoreContactInformation first checks if the XML file already exist then if the file exist it simply updates the file or else creates a new XML file with the provided user data.
     *
     */
    import java.io.File;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import javax.xml.transform.OutputKeys;
    import javax.xml.transform.TransformerException;

    import org.w3c.dom.Attr;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;

    import java.util.Scanner;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;


    public class StoreContactInformation {

        File f;
        String filePathString ;
        DocumentBuilderFactory docFactory ;
        DocumentBuilder docBuilder ;
        Document doc;
        TransformerFactory transformerFactory;
        Transformer transformer;
        DOMSource source;
        StreamResult result;
        String FirstName;
        String LastName;
        long PhoneNumber;
        int choice;
        Scanner reader;
        OutputKeys OutputKeys;

        StoreContactInformation(String fn, String ln, long pn) throws Exception {

            filePathString="PhoneBook.xml"; //File Path is the current working directory. 
            f = new File(filePathString);
            FirstName=fn;
            LastName=ln;
            PhoneNumber=pn;
            docFactory = DocumentBuilderFactory.newInstance();
            docBuilder = docFactory.newDocumentBuilder();
            transformerFactory = TransformerFactory.newInstance();

            // check if the XML file exist already !        
            if(f.exists() && !f.isDirectory()) {
                //if exist
                UpdateXMLFile();
                WriteToXMLFile(); 
            }else{
                //if do not exist
                CreateXMLFile(); 
                WriteToXMLFile();
            } 


        }
        /**
        *
        * The function CreateXMLFile creates a new XML file if one doesn't exist already. 
        * The first set of data stored in the XML file is given the unique id="1".
        * The root element of the XML file is "ContactInformation" which contains child nodes "Contact" with there unique ids.
        * The element "contact further contains child nodes "FirstName","LastName" and "PhoneNumber".
        */
        void CreateXMLFile(){

            doc = docBuilder.newDocument();
            Element rootElement = doc.createElement("ContactInformation");
            doc.appendChild(rootElement);
            Element contact = doc.createElement("Contact");
            rootElement.appendChild(contact);
            Attr attr = doc.createAttribute("id");
            attr.setValue("1");
            contact.setAttributeNode(attr);
            Element firstname = doc.createElement("FirstName");
            firstname.appendChild(doc.createTextNode(FirstName));
            contact.appendChild(firstname);
            Element lastname = doc.createElement("LastName");
            lastname.appendChild(doc.createTextNode(LastName));
            contact.appendChild(lastname);
            Element PN = doc.createElement("PhoneNumber");
            PN.appendChild(doc.createTextNode(java.lang.Long.toString(PhoneNumber)));
            contact.appendChild(PN);

        }
        /**
        *
        * The function WriteToXMLFile is responsible for writing the data into output XML file "PhoneBook.xml".
        * WriteToXMLFile also formats the data to be written into pretty print way with INDENT spaces and line breaks etc.
        */
        void WriteToXMLFile() throws Exception{

            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
            source = new DOMSource(doc);
            result = new StreamResult(new File(filePathString));
            transformer.transform(source, result);
            System.out.println("Contact Saved !");

        }
        /**
        *
        * The function UpdateXMLFile updates the existing XML file with the new user data.
        * The new set of user data gets a unique id for the element "Contact" which is calculated and generated by UpdateXMLFile.
        * 
        */
        void UpdateXMLFile() throws Exception{

            doc = docBuilder.parse(filePathString);
            int AttrValue=1;
            Node ContactInfo = doc.getFirstChild();
            NodeList NumberChildNodes = ContactInfo.getChildNodes();
            for(int i=0;i<NumberChildNodes.getLength();i++)
                {            
                    Node n = NumberChildNodes.item(i);
                    if ("Contact".equals(n.getNodeName())) 
                        {
                            AttrValue+=1;
                        }     
                }     
            Element contact = doc.createElement("Contact");
            ContactInfo.appendChild(contact);
            Attr attr = doc.createAttribute("id");
            attr.setValue(Integer.toString(AttrValue));
            contact.setAttributeNode(attr);
            Element firstname = doc.createElement("FirstName");
            firstname.appendChild(doc.createTextNode(FirstName));
            contact.appendChild(firstname);
            Element lastname = doc.createElement("LastName");
            lastname.appendChild(doc.createTextNode(LastName));
            contact.appendChild(lastname);
            Element PN = doc.createElement("PhoneNumber");
            PN.appendChild(doc.createTextNode(java.lang.Long.toString(PhoneNumber)));
            contact.appendChild(PN);

        }


    }
Enter Your FirstName = 
xxxxxxxx
Enter Your LastName = 
yyyyyyyy
Enter Your PhoneNumber = 
7896456123693
 void WriteToXMLFile() throws Exception{

        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        source = new DOMSource(doc);
        result = new StreamResult(new File(filePathString));
        transformer.transform(source, result);
        System.out.println("Contact Saved !");

    }
错误:

java.lang.NullPointerException
at xmlphonebook.StoreContactInformation.WriteToXMLFile(StoreContactInformation.java:105)
at xmlphonebook.StoreContactInformation.<init>(StoreContactInformation.java:65)
at xmlphonebook.XMLPhoneBook.storeContactInfo(XMLPhoneBook.java:35)
at xmlphonebook.XMLPhoneBook.main(XMLPhoneBook.java:43)

请告诉我我犯了什么错误

我在我的工作区复制了你所有的类,确实有NPE,但正如我在之前的一篇评论中提到的,
transformer.setOutputProperty(OutputKeys.INDENT,“是”)
transformer
NULL
,我通过调试和保留断点来检查它,并使用与我的评论中提到的相同的解决方案来修复它

这就是我在你的构造函数中解决它的方法

    StoreContactInformation(String fn, String ln, long pn) throws Exception {
        filePathString="PhoneBook.xml"; //File Path is the current working directory. 
        f = new File(filePathString);
        FirstName=fn;
        LastName=ln;
        PhoneNumber=pn;
        docFactory = DocumentBuilderFactory.newInstance();
        docBuilder = docFactory.newDocumentBuilder();
        transformerFactory = TransformerFactory.newInstance();

        /******* added this line ******************/
        transformer=transformerFactory.newTransformer(); 
        /******* added this line ******************/

        // check if the XML file exist already !        
        if(f.exists() && !f.isDirectory()) {
            //if exist
            UpdateXMLFile();
            WriteToXMLFile(); 
        }else{
            //if do not exist
            CreateXMLFile(); 
            WriteToXMLFile();
        } 
    }
得到了这个输出

输入您的名字=xxxx

输入您的姓氏=yyyy

输入您的电话号码=123456

联系人已保存


奇怪的名字!您的getter无效,并通过调用setter更新对象!为什么要使用那么多实例字段而不是局部变量?这使得关于对象状态的争论变得非常困难,这可能是您现在无法说出NPE原因的原因。我猜这是您的行号105,
transformer.setOutputProperty(OutputKeys.INDENT,“yes”),在构造函数中,我没有看到
transformer
变量被初始化。也许这会有帮助,
transformer=TransformerFactory.newTransformer()
@Shrikant我已经厌倦了,而且还是一样的。@isnot2bad抱歉编程不好,我对这个很陌生。那么,您能告诉我们您的线路号是105吗