我正在創建一個身體質量指數計算器來練習創建一個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;
}
}
可能的複製(http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – xenteros