[英]Android Eclipse String Txt + Edittext + String Txt = Crash
[英]Android Eclipse EditText crash
我正在尝试累积GPA应用程序。 它包含7个editTexts
和一个textView
。 其中一项用于课程数量,其他用于课程GPA。 当我将其用作6门课程时,它可以工作,但是当我将其用作3门课程为例时,则必须让其中3门为空,否则应用程序崩溃。
public class MainActivity extends Activity {
EditText e1, e2, e3, e4, e5, e6, e7;
TextView t1;
Button b1, b2;
double a=0;
double b=0;
double c=0;
double d=0;
double e=0;
double f=0;
double g=0;
double h=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
e1=(EditText)findViewById(R.id.editText1);
e2=(EditText)findViewById(R.id.editText2);
e3=(EditText)findViewById(R.id.editText3);
e4=(EditText)findViewById(R.id.editText4);
e5=(EditText)findViewById(R.id.editText5);
e6=(EditText)findViewById(R.id.editText6);
e7=(EditText)findViewById(R.id.editText7);
t1=(TextView)findViewById(R.id.textView3);
b2=(Button)findViewById(R.id.button2);
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
a=Double.parseDouble(e1.getText().toString());
b=Double.parseDouble(e2.getText().toString());
c=Double.parseDouble(e3.getText().toString());
d=Double.parseDouble(e4.getText().toString());
e=Double.parseDouble(e5.getText().toString());
f=Double.parseDouble(e6.getText().toString());
g=Double.parseDouble(e7.getText().toString());
h= ((a+b+c+d+e+f)/g);
t1.setText(Double.toString(h));
我尝试了这段代码:
{
if (g==3)
e4.setText("0");
e5.setText("0");
e6.setText("0");
}
但同样的事情发生了。 注意:e7 =课程数
当您保持edittext的任何一个为空时,您的代码将崩溃,例如:如果editext e1为空,则下面的代码将无法正常工作,因为getText()。toString()没有任何数据
a=Double.parseDouble(e1.getText().toString());
你必须喜欢
if(!e1.getText().toString().equals(""))
{
a=Double.parseDouble(e1.getText().toString());
}
至于所有.....
像这样修改您的getText
行:
String e1 = e1.getText().toString();
a= e1.equals("")?0:Double.parseDouble(e1);
这将防止您现在必须获取NumberFormatException
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.