我正在创建一个身体质量指数计算器来练习创建一个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