据我所知,我输入了正确的try catch语句来停止NumberFormatException ... NullPointerException可能来自于此:
TextView tvfin = null;
tvfin.setText(fin+"");
tvfin = (TextView)findViewById(R.id.tvfinalgrade);
这三行将在OnClickListener中,但我还没有创建它,我不确定这是否会导致问题? 非常感谢任何帮助!
package wilson.GC;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
public class GFActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.getfinal);
double q1, q2, ex, fin;
EditText etq1, etq2, eteg;
etq1 = (EditText)findViewById(R.id.editText1);
try{
q1 = Double.parseDouble(etq1.getText().toString());
} catch (NumberFormatException e) {
q1=0;
}
etq2 = (EditText)findViewById(R.id.editText2);
try{
q2 = Double.parseDouble(etq2.getText().toString());
} catch (NumberFormatException e){
q2 = 0;
}
eteg = (EditText)findViewById(R.id.editText3);
try{
ex = Double.parseDouble(eteg.getText().toString());
} catch (NumberFormatException e){
ex = 0;
}
fin = 0.4*q1+0.4*q2+0.2*ex;
if(fin == (int)fin){
System.out.println((int)fin);
}
else{
fin = 0.01*((int)(fin*100));
System.out.println(fin);
}
TextView tvfin = null;
tvfin.setText(fin+"");
tvfin = (TextView)findViewById(R.id.tvfinalgrade);
}
}
答案 0 :(得分:2)
在设置文本之前尝试设置tvfin:
TextView tvfin = (TextView)findViewById(R.id.tvfinalgrade);
tvfin.setText(fin+"");
答案 1 :(得分:2)
您尝试在初始化之前设置TextView
的值。这肯定会给你一个NullPointerException
。改变这个:
TextView tvfin = null;
tvfin.setText(fin+"");
tvfin = (TextView)findViewById(R.id.tvfinalgrade);
为:
TextView tvfin = (TextView)findViewById(R.id.tvfinalgrade);
tvfin.setText(fin+"");