2017-01-21 27 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); 
}