0

再会。我在 Eclipse 中为 android 编写了应用程序,当 EditText 为空时应用程序崩溃。我尝试了很多方法,但它不起作用。当我输入它并且 EditText 是空的时,它会崩溃。对不起我的英语不好。这是我的代码的一部分:

public class MainActivity extends Activity implements OnClickListener {

TextView mnozstvo;
TextView percento;
TextView hmotnost;
TextView vysledok1;
TextView vysledok2;
TextView text;
RadioButton muz1;
RadioButton zena1;
Button vysledok;
EditText coo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

text = (TextView)this.findViewById(R.id.text);

mnozstvo = (TextView)this.findViewById(R.id.dl);


percento = (TextView)this.findViewById(R.id.per);

hmotnost = (TextView)this.findViewById(R.id.kg);

vysledok1 = (TextView)this.findViewById(R.id.krv);

vysledok2 = (TextView)this.findViewById(R.id.dych);

muz1 = (RadioButton)this.findViewById(R.id.muz);

zena1 = (RadioButton)this.findViewById(R.id.zena);

vysledok = (Button)this.findViewById(R.id.vysledok);

vysledok.setOnClickListener(this);


}
.................
public void convertDollarsToEuros() {
double val = Double.parseDouble(mnozstvo.getText().toString());
double val1 = Double.parseDouble(percento.getText().toString());
double val2 = Double.parseDouble(hmotnost.getText().toString());

vysledok1.setText(Double.toString((val*val1*0.8)/(val2*0.68)));
vysledok2.setText(Double.toString(((val*val1*0.8)/(val2*0.68))/(2.1)));

text.setText(Double.toString(((val*val1*0.8)/(val2*0.68))*6.6164));



}

public void convertEurosToDollars() {

double val = Double.parseDouble(mnozstvo.getText().toString());
double val1 = Double.parseDouble(percento.getText().toString());
double val2 = Double.parseDouble(hmotnost.getText().toString());

vysledok1.setText(Double.toString((val*val1*0.8)/(val2*0.55)));
vysledok2.setText(Double.toString(((val*val1*0.8)/(val2*0.55))/(2.1)));
text.setText(Double.toString(((val*val1*0.8)/(val2*0.55))*6.6164));

有人能帮我吗?

4

2 回答 2

0

Double.parseDouble()将引发 NumberFormatException。

但是,您可以在尝试解析字符串之前检查字符串的长度,而不是等待异常发生然后处理它。

您的代码应如下所示:

public void convertEurosToDollars() {
    double val = 0;
    double val1= 0;
    double val2= 0;
    if (mnozstvo.getText().length() > 0 ) {
        val = Double.parseDouble(mnozstvo.getText().toString());
    }
    if (percento.getText().length() > 0 ) {
        val2 = Double.parseDouble(percento.getText().toString());
    }
    if (hmotnost.getText().length() > 0 ) {
        val3 = Double.parseDouble(hmotnost.getText().toString());
    }       


    vysledok1.setText(Double.toString((val*val1*0.8)/(val2*0.55)));
    vysledok2.setText(Double.toString(((val*val1*0.8)/(val2*0.55))/(2.1)));
    text.setText(Double.toString(((val*val1*0.8)/(val2*0.55))*6.6164));
   }
于 2013-02-21T20:58:14.903 回答
0

http://docs.oracle.com/javase/6/docs/api/java/lang/Double.html#parseDouble(java.lang.String)

parseDouble 将不高兴给出null""

于 2013-02-21T20:52:48.420 回答