2011-12-26 51 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