Exception in thread "main" java.lang.NullPointerException Problem!!
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 7 of 7

Thread: Exception in thread "main" java.lang.NullPointerException Problem!!

  1. #1
    Join Date
    Jun 2009
    Posts
    1

    Question Exception in thread "main" java.lang.NullPointerException Problem!!

    hi,
    I am new in java programming

    i run this program and get error message
    (Exception in thread "main" java.lang.NullPointerException at CheckAge.main(CheckAge.java:12)

    here is my full coding:

    import java.util.Scanner;
    class CheckAgeForDiscount {
    public static void main(String args[]) {
    Scanner myScanner = new Scanner(System.in);
    int age;
    double price = 0.00;
    char reply;

    System.out.print("How old are you? ");
    age = myScanner.nextInt();
    System.out.print("Have a coupon? (Y/N) ");
    reply = myScanner.findInLine(".").charAt(0);

    if (age >= 12 && age < 65) {
    price = 9.25;
    }
    if (age < 12 || age >= 65) {
    price = 5.25;
    }
    if ((reply == 'Y' || reply == 'y') &&
    (age >= 12 && age < 65)) {
    price -= 2.00;
    }
    System.out.print("Please pay $");
    System.out.print(price);
    System.out.print(". ");
    System.out.println("Enjoy the show!");
    }
    }

    Can anyone tell me the reason this error happen and a solution to this problem.
    Thanks.

  2. #2
    Join Date
    May 2006
    Location
    UK
    Posts
    4,474

    Re: Exception in thread "main" java.lang.NullPointerException Problem!!

    findInLine() returns null if the pattern isn't found and if this happens the call to charAt(0) will throw a NullPointerException.

    To get around this problem split this line into two lines and test the value returned by findInLine() for null before calling charAt().

  3. #3
    Join Date
    Nov 2010
    Posts
    2

    Re: Exception in thread "main" java.lang.NullPointerException Problem!!

    I'm another beginner with the code and can you please explain how should I write the code to split it ?

  4. #4
    Join Date
    May 2006
    Location
    UK
    Posts
    4,474

    Re: Exception in thread "main" java.lang.NullPointerException Problem!!

    Code:
    reply = myScanner.findInLine(".").charAt(0);
    This line calls the charAt() method on the value returned by the findInLine() method. So to split it into 2 lines of code make the call to the findInLine() method and assign the returned value to a local String variable and then make to call to the charAt() method on the String variable.

    You will then need to insert a test for null in between these two lines.
    Posting code? Use code tags like this: [code]...Your code here...[/code]
    Click here for examples of Java Code

  5. #5
    Join Date
    Nov 2010
    Posts
    2

    Re: Exception in thread "main" java.lang.NullPointerException Problem!!

    Thanks you !

  6. #6
    Join Date
    Jan 2012
    Posts
    1

    Re: Exception in thread "main" java.lang.NullPointerException Problem!!

    Hi everybody!

    I am also new in Java programming. When I run my code, I get error code:
    Exception in thread "main" java.lang.NullPointerException at mcds.Call.CheckSubscriberTokens(Call.java:118)

    My full code is:

    import java.io.BufferedReader;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.io.StringReader;
    import java.io.StringWriter;
    import java.io.Writer;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.net.URLConnection;

    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;


    import org.w3c.dom.Document;
    import org.w3c.dom.NodeList;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;

    import com.sun.org.apache.xml.internal.serialize.OutputFormat;
    import com.sun.org.apache.xml.internal.serialize.XMLSerializer;

    public class Call {

    public String CheckSubscriberTokens ( String action, String subscriberid, String ispid, String submit ) throws MalformedURLException, IOException
    {
    //Code to make a webservice HTTP request
    String responseString = "";
    String outputString = "";

    String wsURL = "some url";

    URL url = new URL(wsURL);

    URLConnection connection = url.openConnection();

    HttpURLConnection httpConn = (HttpURLConnection)connection;

    ByteArrayOutputStream bout = new ByteArrayOutputStream();

    String xmlInput =
    " <soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"some url/\">n" +
    " <soapenv:Header/>\n" +
    " <soapenv:Body>\n" +
    " <web:checksubscribertokens>\n" +
    " <!--Optional:-->\n" +
    " <web:action>" + action + "</web:action>\n" +
    " <web:subid>" + subscriberid + "</web:subid>\n" +
    " <web:ispid>" + ispid + "</web:ispid>\n" +
    " <web:submit>" + submit + "</web:submit>\n" +
    " </web:checksubscribertokens>\n" +
    " </soapenv:Body>\n" +
    " </soapenv:Envelope>";

    byte[] buffer = new byte[xmlInput.length()];

    buffer = xmlInput.getBytes();

    bout.write(buffer);

    byte[] b = bout.toByteArray();

    String SOAPAction = "some url";

    // Set the appropriate HTTP parameters.

    httpConn.setRequestProperty("Content-Length",String.valueOf(b.length));
    httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
    httpConn.setRequestProperty("SOAPAction", SOAPAction);
    httpConn.setRequestMethod("POST");
    httpConn.setDoOutput(true);
    httpConn.setDoInput(true);

    OutputStream out = httpConn.getOutputStream();

    //Write the content of the request to the outputstream of the HTTP Connection.
    out.write(b);
    out.close();

    //Ready with sending the request.
    //Read the response.
    InputStreamReader isr = new InputStreamReader(httpConn.getInputStream());
    BufferedReader in = new BufferedReader(isr);


    //Write the SOAP message response to a String.

    while ((responseString = in.readLine()) != null) {
    outputString = outputString + responseString;
    System.out.println("outputString");
    }

    //Parse the String output to a org.w3c.dom.Document and be able to reach every node with the org.w3c.dom API.

    Document document = parseXmlFile(outputString);
    System.out.println("1");

    NodeList nodeLst = document.getElementsByTagName("result");
    System.out.println("2");

    String Result = nodeLst.item(0).getTextContent(); --- IN THIS ROW I HAVE ERROR!!!
    System.out.println("3");
    // System.out.println("Odgovor_IN: " + Result);


    //Write the SOAP message formatted to the console.
    String formattedSOAPResponse = formatXML(outputString);
    System.out.println(formattedSOAPResponse);
    return Result;
    }


    //format the XML in your String
    public String formatXML(String unformattedXml) {

    try {

    Document document = parseXmlFile(unformattedXml);

    OutputFormat format = new OutputFormat(document);
    format.setIndenting(true);
    format.setIndent(3);
    format.setOmitXMLDeclaration(true);

    Writer out = new StringWriter();

    XMLSerializer serializer = new XMLSerializer(out, format);
    serializer.serialize(document);

    return out.toString();

    } catch (IOException e) {
    throw new RuntimeException(e);

    }
    }


    private Document parseXmlFile(String in) {
    try {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    InputSource is = new InputSource(new StringReader(in));

    return db.parse(is);

    } catch (ParserConfigurationException e) {
    throw new RuntimeException(e);

    } catch (SAXException e) {
    throw new RuntimeException(e);

    } catch (IOException e) {
    throw new RuntimeException(e);

    }
    }
    }

    Please, can you help me?

    Thanks!

  7. #7
    Join Date
    May 2006
    Location
    UK
    Posts
    4,474

    Re: Exception in thread "main" java.lang.NullPointerException Problem!!

    Please do not tack your question onto someone else's old thread, start your own thread and always post code in code tags.

    Have you tried printing out the value nodeLst and then nodeLst.item(0) to see which one is null?
    Posting code? Use code tags like this: [code]...Your code here...[/code]
    Click here for examples of Java Code

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center