Hey guys, I am aware that there are numerous Java apps available for computing a number's factorial, however I am having trouble with Android. My code is as follows. Thanks
package com.droidacid.apticalc.aptitudes;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.droidacid.apticalc.R;
public class AptiFactorial extends Activity implements android.view.View.OnClickListener{
EditText number;
TextView answer;
Button calculate;
long factorial = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.apti_factorial);
initialize();
calcFactorial();
}
private void initialize() {
number = (EditText) findViewById(R.id.et_apti_number);
answer = (TextView) findViewById(R.id.tv_apti_answer);
calculate = (Button) findViewById(R.id.b_apti_calc);
calculate.setOnClickListener(this);
}
private void calcFactorial() {
if (number.getText().toString().equals("")) number.setText("0");
int num = Integer.parseInt(number.getText().toString());
for(int i = 1; i<=num; i++){
factorial = i * factorial;
}
}
@Override
public void onClick(View v) {
calcFactorial();
answer.setText("Factorial of " + number.getText().toString() + " is : " + factorial);
}
}
This is my code, and I need to know how to set the hint to something other than 0. However, removing if (number.getText (). number = toString().equals("")) setText("0");
receiving a NullPointerException after that Additionally, the calculation is correct the first time, but if I recalculate, the result is incorrect. Because I am utilising the factorial value directly, I believe there is a looping issue.