2016-01-10 123 views
0

我是Android應用程序開發的初學者。我的代碼如下 - 如何解決數字格式異常在此代碼 -如何解決:數字格式異常無效int:「」

公共類InterestActivity擴展AppCompatActivity {

private EditText editAmount; 
private EditText editInterest; 
private EditText editDuration; 

private TextView resultView; 
private Button Calculate; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_interest); 

    editAmount = (EditText) findViewById(R.id.editAmount); 
    editInterest = (EditText) findViewById(R.id.editInterest); 
    editDuration = (EditText) findViewById(R.id.editDuration); 
    resultView = (TextView) findViewById(R.id.resultView); 
    Calculate = (Button) findViewById(R.id.button4); 
} 

    public void interestCalculate (View v) { 
     resultView= (TextView) findViewById(R.id.resultView); 
     Calculate = (Button) findViewById(R.id.button4); 

     int a = Integer.parseInt(editAmount.getText().toString()); 
     int i = Integer.parseInt(editInterest.getText().toString()); 
     int d = Integer.parseInt(editDuration.getText().toString()); 

     int ir= i/100; 

     float res = a*ir*d; 
     int intres= (int) res; 
    resultView.setText(Integer.toString(intres)); 
    }} 

回答

0
public void interestCalculate (View v) { 
     resultView= (TextView) findViewById(R.id.resultView); 
     Calculate = (Button) findViewById(R.id.button4); 

     int a = 0; 
     int i = 0; 
     int d = 0; 
     try{ 
      a= Integer.parseInt(editAmount.getText().toString()); 
     }catch(Throwable e){ 
      Toast.makeText(getApplicationContext(),"editAmount"+ "'s value is not a Integer",Toast.LENGTH_LONG); 
     } 
     try{ 
      i = Integer.parseInt(editInterest.getText().toString()); 

     }catch(Throwable e){ 
      Toast.makeText(getApplicationContext(),"editInterest"+ "'s value is not a Integer",Toast.LENGTH_LONG); 
     } 
     try{ 
      d = Integer.parseInt(editDuration.getText().toString()); 
     }catch(Throwable e){ 
      Toast.makeText(getApplicationContext(),"editDuration"+ "'s value is not a Integer",Toast.LENGTH_LONG); 
     } 


     int ir= i/100; 

     float res = a*ir*d; 
     int intres= (int) res; 
     resultView.setText(Integer.toString(intres)); 
    }} 
0

您分配意見暫時的局部變量,而不是類的屬性。

簡短的解決方案:

裏面的onCreate所有其他任務之前editAmount = ...

同樣刪除EditText

如果你想繼續Android編程,你應該明白爲什麼這將工作。這可能會幫助你:What is the difference between field, variable, attribute, and property in Java POJOs?

+0

謝謝!此代碼中是否存在其他錯誤,因爲您的解決方案解決了空點異常,但仍然存在其他一些錯誤。再次感謝。 – Rohit

+0

如果你有新的問題,你應該問一個新的問題,而不是編輯問題,所以有相同問題的其他人可以找到你的舊問題。如果你得到一個NumberformatException,可能是因爲editText框中沒有有效的數字。 @tiny陽光的答案顯示瞭如何處理這種情況。 – F43nd1r

相關問題