[英]Errors with java applet
我正在嘗試編寫一個小程序,該程序將計算四個輸入框的平均數量,或者根據單擊哪個框清除所有字段。 我認為我大致上是對的,但是某個地方出現錯誤,導致出現以下錯誤聲明:線程“ 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;
}
閱讀異常。 它被拋出這一行:
myarray[0] = Integer.parseInt(textField1.getText());
問題在於它不能將String解析為數字,因為它有空格(例如10
)。 您需要做的是使用trim()刪除開頭和結尾的空格:
myarray[0] = Integer.parseInt(textField1.getText().trim());
那應該可以解決NumberFormatException,但是其他錯誤仍然存在。
錯誤消息告訴您確切是什么地方。 您正在嘗試解析" 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("");
}
這將減少數字為String的空格的風險。
"Errors with java applet"
告訴我們有關您的實際問題的信息很少,並且可能不會吸引有關該特定問題的專家。 更好的問題標題可能是"NumberFormatException problem when parsing applet TextField text"
或類似的內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.