Search code examples
javaparsingjoptionpane

Am I using parse right?


As far as I can tell i'm doing this right ( Clearly not though ) I am trying to change strings into Doubles because I can't get a double from a JPane. it is giving me an object not initialized error. How do I fix it?

import javax.swing.JOptionPane;

    public class jwindows {
    public static void main (String args[]) {

        double a, b, c;
        double sum = a + b + c;
        double product = a * b * c ;
        double avarge = a * b * c / 3;

    String stringA = JOptionPane.showInputDialog
            (null, "Please enter first number");
        a = Double.parseDouble(stringA);

    String stringB = JOptionPane.showInputDialog
            (null, "Please enter second number: ");
        b = Double.parseDouble(stringB);

    String stringC = JOptionPane.showInputDialog
            (null, "Please enter third number: ");  
        c = Double.parseDouble(stringC);

        JOptionPane.showInternalMessageDialog
        (null, "The sum of the 3 numbers is " + sum);

        JOptionPane.showInternalMessageDialog
        (null, "The avarge of the 3 numbers is " + avarge);

        JOptionPane.showInternalMessageDialog
        (null, "The sum of the 3 numbers is " + product);
    }
}

Solution

  • double a, b, c;
    double sum = a + b + c;
    double product = a * b * c ;
    double avarge = a * b * c / 3;
    

    You just defined variables, but didn't initialize them. Move them below right after all values for a, b, c obtained.

    One more thing: Change showInternalMessageDialog to showMessageDialog as you don't have parent component at all.