سؤال

I'm trying to parse a string from a text field into a double:

Double.parseDouble(variable.getText())

Yet the program throws the following exception:

error: Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at gpacalculator.xGPA.calGPAbtnActionPerformed(xGPA.java:341)

Here are my declarations:

private void calGPAbtnActionPerformed(java.awt.event.ActionEvent evt) {                                                
  String q1,q2,q3,q4,q5,q6,q7,q8,w1,w2,w3,w4,w5,w6,w7,w8;
    q1 = course1.getText();
    q2 = course2.getText();
    q3 = course3.getText();
    q4 = course4.getText();
    q5 = course5.getText();
    q6 = course6.getText();
    q7 = course13.getText();
    q8 = course15.getText();
    w1 = course7.getText();
    w2 = course8.getText();
    w3 = course9.getText();
    w4 = course10.getText();
    w5 = course11.getText();
    w6 = course12.getText();
    w7 = course14.getText();
    w8 = course16.getText();

    gpaCal.setUnits1(Double.parseDouble(q1));
    gpaCal.setUnits2(q2);
    gpaCal.setUnits3(q3);
    gpaCal.setUnits4(q4);
    gpaCal.setUnits5(q5);
    gpaCal.setUnits6(q6);
    gpaCal.setUnits7(q7);
    gpaCal.setUnits8(q8);
    gpaCal.setGrade1(w1);
    gpaCal.setGrade2(w2);
    gpaCal.setGrade3(w3);
    gpaCal.setGrade4(w4);
    gpaCal.setGrade5(w5);
    gpaCal.setGrade6(w6);
    gpaCal.setGrade7(w7);
    gpaCal.setGrade8(w8);
}

Note: I only tried to parse the first one to display the idea of the code.

هل كانت مفيدة؟

المحلول 2

I bet your NPE is propagated up the call stack, that's why it's caught at xGPA.java:341.

final String variableText = (variable != null) ? variable.getText() : null;
final Double result = (variableText != null) ? Double.parseDouble(variableText) : 0;

نصائح أخرى

From the Double#parseDouble(String) JavaDoc: Throws NullPointerException if the string is null

You need to check for null (and perhaps on the variable as well if that can be null) before parsing, so something like this:

if(variable != null && variable.getText() != null) {
    Double.parseDouble(variable.getText()
}

Check if string is null first. i.e. If no text has been entered in your textfield, this will return an error.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top