0

据我所知,我做得对(显然不是)我试图将字符串更改为双打,因为我无法从 JPane 获得双打。它给了我一个对象未​​初始化的错误。我如何解决它?

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);
    }
}
4

3 回答 3

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

您只是定义了变量,但没有初始化它们。在获得 a、b、c 的所有值后,将它们移到右下方。

还有一件事:更改showInternalMessageDialogshowMessageDialog根本没有父组件。

于 2013-04-13T14:48:27.353 回答
0

变量a, b,c尚未初始化(并且不包含任何值)等等sumproduct因此avarage无法计算。要解决这个问题,只需移动sum,直到你解析, product, . 像这样:avargeabc

import javax.swing.JOptionPane;

public class jwindows {
public static void main (String args[]) {
double a, b, c;

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);

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

JOptionPane.showMessageDialog(null, "The sum of the 3 numbers is " + sum);
JOptionPane.showMessageDialog(null, "The avarge of the 3 numbers is " + avarge);
JOptionPane.showMessageDialog(null, "The sum of the 3 numbers is " + product);
}
}
于 2013-04-13T14:44:30.553 回答
0

您不会得到变量sum、averge 和 product 的预期值。您在开始时计算它的值:

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

你必须在这里得到编译错误,因为 a,b 和 c 是局部变量,在使用它们之前没有初始化。所以编译器在这种情况下会抛出错误。即使将它们初始化为某个值,在从 showInputDialog 为这些变量赋值之后,您也必须计算 sum、averge 和 prodcut 的值。

尝试使用这个:

sum = a+b+c;

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

     averge = (a+b+c)/3;
    JOptionPane.showInternalMessageDialog
    (null, "The avarge of the 3 numbers is " + avarge);
    product = a*b*c;
    JOptionPane.showInternalMessageDialog
    (null, "The sum of the 3 numbers is " + product);
于 2013-04-13T14:45:01.187 回答