2017-01-21 24 views
0

我正在创建一个身体质量指数计算器来练习创建一个GUI。但是,我不明白为什么我得到如下所示的错误。我在想我试图错误地显示BMI的价值。有人可以帮忙吗?身体质量指数计算器 - 错误

在线程 “主” 显示java.lang.NullPointerException在 源在Main.main(Main.java:5)异常。(Source.java:21)

import javax.swing.JFrame; 

public class Main { 
public static void main (String args []) { 
    Source sourceObject = new Source(); 
    sourceObject.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    sourceObject.setSize(275,180); 
    sourceObject.setVisible(true); 

} 

} 

import java.awt.FlowLayout; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JOptionPane; 

public class Source extends JFrame { 

private JLabel item1; 
private JLabel item2; 
private JLabel item3; 
private String weight, height; 
private int BMI; 

public Source() { 
    super("Title"); 
    setLayout(new FlowLayout()); 
    item1 = new JLabel("Text"); 
    item1.setToolTipText("This appears on hover"); 
    weight = JOptionPane.showInputDialog(null, "Weight: "); 
    height = JOptionPane.showInputDialog(null, "Height: "); 
    item3.setText(String.valueOf(BMI)); 
    add(item1); 
    add(item2); 
    add(item3); 

} 
int BMICalc() { 
    int weig = Integer.parseInt(weight); 
    int heig = Integer.parseInt(height); 
    int BMI = (weig)/(heig * heig); 
    return BMI; 

} 


} 
+2

可能的复制(http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – xenteros

回答

1

实际上item2item3被声明但从未实例化。

但实际的问题是你正在调用item3的方法。

Source构造函数中实例化所有具有已知值的字段。

+0

你在哪看到我在item2上调用方法? – helloumarian

+0

我会说item3对不起 – davidxxx

+0

我还不明白什么是错的,你能解释一下多一点吗? – helloumarian

0

你错过了创造的JLabel 2和3试试这个:什么是一个NullPointerException,以及如何解决呢]的

public Source() { 
    super("Title"); 
    setLayout(new FlowLayout()); 
    item1 = new JLabel("Text"); 
    item1.setToolTipText("This appears on hover"); 

    item2 = new JLabel("Text"); 

    weight = JOptionPane.showInputDialog(null, "Weight: "); 
    height = JOptionPane.showInputDialog(null, "Height: "); 
    BMICalc();   

    item3 = new JLabel("Text"); 
    item3.setText(String.valueOf(BMI)); 
    add(item1); 
    add(item2); 
    add(item3); 
}