有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Try catch不起作用(总是执行catch代码)

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

package boston.project;

import 安卓.app.Activity;
import 安卓.os.Bundle;
import 安卓.view.View;
import 安卓.widget.Button;
import 安卓.widget.EditText;
import 安卓.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);
        }
    });

}
}

共 (1) 个答案

  1. # 1 楼答案

    您正在尝试在创建EditText之后(通过调用setContentView)从EditText获取文本。它们都是空的-不包含文本。自从

    Integer.parseInt("");
    

    抛出一个异常,所有的catch块都会被执行(这意味着它们实际上可以工作,而不是相反)