2011-12-26 72 views
-2

如果任何人都可以帮助我,我将不胜感激!它应该将三个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); 
     } 
    }); 

} 
} 
+0

你在说什么问题 - 启动时崩溃? Imho EditText可能未初始化。 – fuzzy 2011-12-26 23:04:14

回答

3

您正在试图从EditTexts文本您创建它们只是后(通过调用的setContentView)。他们都是空的 - 不包含任何文字。并且由于

Integer.parseInt(""); 

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

+0

so..sorry如果这是一个愚蠢的问题,但是,我会如何解决这个问题?三个EditText字段(etA,etB和etC)由用户输入定义。那么我将如何正确地将其转换为整数? – Wilson 2011-12-26 23:05:44

+0

最简单的方法是将代码移动到按钮的onClickListener中。 – user1234567 2011-12-26 23:07:11

+0

非常感谢! – Wilson 2011-12-26 23:09:07