我使用解析权吗?

问题描述:

据我可以告诉我这样做的权利(显然不是) 我想改变字符串成双打,因为我无法从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); 
    } 
} 
+0

你能发表确切的错误吗? –

+0

如果您没有收到NumberFormatException,那么您解析正确。 –

+0

当您尝试计算总和平均值和乘积时,a,b和c不需要分配给任何东西。移动这些定义直到你解析后c – Charlie

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

你刚才定义的变量,但没有初始化。在获得a,b,c的所有值后,将它们移到右下方。

还有一件事:将showInternalMessageDialog更改为showMessageDialog,因为根本没有父组件。

+0

感谢队友,我实际上只是想问为什么我没有收到盒子。救了我一些麻烦:) – Blank1268

变量abc尚未初始化(不包含任何值)等sumproductavarage无法计算。要解决此问题,只需移动sum,productavarge,直到解析完a,b,c。就像这样:

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

你不会得到变量总和,averge和产品的预期值。您在开始计算它的价值:

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