【问题标题】:Try catch does not work (always does catch code)尝试捕获不起作用(总是捕获代码)
【发布时间】:2012-01-28 05:03:46
【问题描述】:

如果有人可以帮助我,我将不胜感激!它应该将三个 EditText 变量转换为字符串,然后转换为整数。我添加了异常,因为没有它,程序在启动时崩溃。我不确定问题出在变量的转换中,还是在我的 try catch 代码中,或者两者兼而有之。请帮忙!

package boston.project;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;



public class TheBostonProjectActivity extends Activity {

public EditText aed, bed, ced;
public TextView dtv;
public int a, b, c;
public Button solve;
public double dis;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);


        aed = (EditText)(findViewById(R.id.etA));
                    try {
                        a = Integer.parseInt(aed.getText().toString());
                        } catch (NumberFormatException e) {
                            a = 0;
                        }
        bed = (EditText)(findViewById(R.id.etB));
                    try {
                        b = Integer.parseInt(bed.getText().toString());
                        } catch (NumberFormatException e) {
                            b = 0;
                        }
        ced = (EditText)(findViewById(R.id.etC));
                    try {
                        c = Integer.parseInt(ced.getText().toString());
                        } catch (NumberFormatException e) {
                            c = 0;
                        }

    solve = (Button)(findViewById(R.id.bsolve));

    solve.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // Perform action on click
            dis = (b*b)-(4*a*c);
            dtv = (TextView)findViewById(R.id.tvdis);
            dtv.setText("Discriminant:" + dis);
        }
    });

}
}

【问题讨论】:

  • 您说的问题是什么 - 启动时崩溃? Imho EditText 可能未初始化。

标签: java android exception try-catch


【解决方案1】:

您正试图在创建它们之后从 EditTexts 获取文本(通过调用 setContentView)。它们都是空的 - 不包含任何文本。因为

Integer.parseInt("");

抛出一个异常,所有的 catch 块都被执行(这意味着,它们确实有效,而不是相反)。

【讨论】:

  • so..对不起,如果这是一个愚蠢的问题,但是,我将如何解决这个问题?三个 EditText 字段(etA、etB 和 etC)由用户输入定义。那么我如何正确地将其转换为整数呢?
  • 最简单的方法是将代码移动到按钮的 onClickListener 中。
猜你喜欢
  • 2018-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-25
  • 1970-01-01
  • 1970-01-01
  • 2017-09-12
  • 1970-01-01
相关资源
最近更新 更多