gpt4 book ai didi

java - 体重指数计算器 - 错误

转载 作者:行者123 更新时间:2023-12-01 08:59:39 25 4
gpt4 key购买 nike

我正在创建一个体重指数计算器来练习创建 GUI。但是,我无法弄清楚为什么会出现如下所示的错误。我认为我试图错误地显示 BMI 值。有人可以帮忙吗?

Exception in thread "main" java.lang.NullPointerException at Source.(Source.java:21) at Main.main(Main.java:5)

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;

}


}

最佳答案

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

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

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

关于java - 体重指数计算器 - 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41784849/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com