[英]Cannot parse String to a Float (java)
我正在尝试接受来自文本字段的用户输入。 由于某种原因,字符串不能被接受,给出一个错误。 这是我的代码。 我将其放在构造函数上,因此只需要从主方法调用它即可。 我将初始化放在构造函数之前。
public Compute2(){
Panel p1 = new Panel();
f1.setLayout(new FlowLayout());
CheckboxGroup g = new CheckboxGroup(); // creates radio buttons
Checkbox C = new Checkbox("Circle", g, false);
Checkbox R = new Checkbox("Rectangle", g, false);
p1.add(C);
p1.add(R);
f1.add(p1); // adds panel 1 to main frame
Panel p2 = new Panel(new GridLayout(4,1));
p2.add(lengthLabel);
p2.add(lengthField);
String l = "";
l = lengthField.getText();
length = Float.parseFloat(l);
p2.add(widthLabel);
p2.add(widthField);
String w = "";
w = widthField.getText();
width = Float.parseFloat(w);
p2.add(heightLabel);
p2.add(heightField);
String h = "";
h = heightField.getText();
height = Float.parseFloat(h);
p2.add(new Label(" ")); // required to "center" the button
p2.add(compute);
f1.add(p2); // adds panel 2 to main frame
compute.addActionListener(this);
compute.addActionListener(new ActionListener() { // when comp button is clicked, it must perform actions
@Override
public void actionPerformed(ActionEvent e) {
String ae = e.getActionCommand();
switch (ae) {
case "Circle":
areaCircle(length);
volumeCircle(length);
break;
case "Rectangle":
areaRectangle(length, width);
volumeRectangle(length, width, height);
break;
}
}
});
Panel p3 = new Panel();
f1.setLayout(new FlowLayout());
p3.add(volume);
volumeField = new TextField(10);
volumeField.setEditable(false);
p3.add(volumeField);
p3.add(area);
areaField = new TextField(10);
areaField.setEditable(false);
p3.add(areaField);
f1.add(p3); // adds panel 3 to main frame
f1.setSize(350, 250);
f1.setVisible(true);
f1.addWindowListener(new WindowAdapter(){ // closes program when "X" icon is clicked.
@Override
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
您写的行
l = lengthField.getText();
length = Float.parseFloat(l);
以此类推。 这是因为l的值为空。 您正在内部构造函数中编写此代码,并期望用户提供输入。 但是,在他甚至不能在您的构造函数中提供输入之前,您都在尝试获取用户从未设置过的文本,因此为空值。 空值不能转换为浮点型。
尝试捕获异常和pribt堆栈跟踪,这将揭示问题出在哪里以及您要解析的值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.