[英]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.