我正在尝试编写一个小程序,它将计算四个输入框的平均数量或清除所有字段,具体取决于单击的框。我认为我大部分都是正确的,但是某处出现错误导致出现以下错误声明: 线程中的异常" AWT-EventQueue-0" java.lang.NumberFormatException:对于输入字符串:" 10"这就是我到目前为止所拥有的:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class blooddriveaverage extends Applet implements ActionListener
{
public void init()
{
Label title = new Label("Blood Drive!");
setBackground(Color.red);
Label label1 = new Label("Department 1 amount: ");
textField1 = new TextField(" ");
avg = new Button("Average");
clear = new Button ("Clear Fields");
avg.addActionListener(this);
clear.addActionListener(this);
Label label2 = new Label("Department 2 amount: ");
textField2 = new TextField(" ");
Label label3 = new Label("Department 3 amount: ");
textField3 = new TextField(" ");
Label label4 = new Label("Department 4 amount: ");
textField4 = new TextField(" ");
add(title);
add(label1);
add(textField1);
add(label2);
add(textField2);
add(label3);
add(textField3);
add(label4);
add(textField4);
add(avg);
add(clear);
avg.setBackground(Color.white);
clear.setBackground(Color.orange);
}
public void actionPerformed(ActionEvent e)
{
setLayout(new FlowLayout());
double average = 0;
int[] myarray = new int[3];
myarray[0] = Integer.parseInt(textField1.getText());
myarray[1] = Integer.parseInt(textField2.getText());
myarray[2] = Integer.parseInt(textField3.getText());
myarray[3] = Integer.parseInt(textField4.getText());
if (e.getSource() == avg)
{
for(int i = 0; i < myarray.length; i++)
{
average += myarray[i];
}
average /=4;
Label avgfield = new Label("Average is" + average);
}
else
{
textField1.setText(" ");
textField2.setText(" ");
textField3.setText(" ");
textField4.setText(" ");
}
}
TextField textField1, textField2, textField3, textField4;
Button avg;
Button clear;
}
答案 0 :(得分:3)
阅读例外情况。抛出这一行:
myarray[0] = Integer.parseInt(textField1.getText());
问题是它无法将String解析为数字,因为它有空格(例如10
)。你需要做的是删除带有trim()的前导和尾随空格:
myarray[0] = Integer.parseInt(textField1.getText().trim());
这应该修复NumberFormatException,但其他错误仍然存在。
答案 1 :(得分:1)
错误消息告诉您确切的错误。您正在尝试解析" 10"
,并且该额外空间具有重要意义。
trim()
以消除前导和尾随空格。例如,改变:
textField2 = new TextField(" ");
和
else
{
textField1.setText(" ");
textField2.setText(" ");
textField3.setText(" ");
textField4.setText(" ");
}
为:
textField2 = new TextField("");
else
{
textField1.setText("");
textField2.setText("");
textField3.setText("");
textField4.setText("");
}
这样可以降低数字字符串中空格的风险。
"Errors with java applet"
很少告诉我们您的实际问题,并且可能无法针对该特定问题吸引专家。一个更好的问题标题可能是,"NumberFormatException problem when parsing applet TextField text"
或类似的东西。