Step1:
Open Android Studio and create a new project with an Empty Activity template.In the res/layout/activity_main.xml file, add an EditText for the user to enter a number and a Button to trigger the calculation:
-
<EditText
android:id="@+id/editTextNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter a positive number"/>
<Button
android:id="@+id/buttonCalculateFactorial"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Calculate Factorial"
android:onClick="calculateFactorial"/>
In the MainActivity.java file, implement the calculateFactorial method:
-
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void calculateFactorial(View view) {
EditText editTextNumber = findViewById(R.id.editTextNumber);
String input = editTextNumber.getText().toString();
if (!input.isEmpty()) {
int number = Integer.parseInt(input);
if (number >= 0) {
Intent intent = new Intent(this, ResultActivity.class);
intent.putExtra("number", number);
startActivity(intent);
} else {
editTextNumber.setError("Please enter a non-negative number");
}
} else {
editTextNumber.setError("Please enter a number");
}
}
}
Step 2:
Create a new activity by right-clicking on the app folder in the Project Explorer, then selecting New -> Activity -> Empty Activity. Name it ResultActivity.In the ResultActivity.java file, retrieve the number from the Intent, calculate its factorial, and display the result:
-
import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class ResultActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
TextView textViewResult = findViewById(R.id.textViewResult);
Intent intent = getIntent();
int number = intent.getIntExtra("number", 0);
long factorial = calculateFactorial(number);
textViewResult.setText("Factorial of " + number + " is " + factorial);
}
private long calculateFactorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * calculateFactorial(n - 1);
}
}
}
In the res/layout/activity_result.xml file, add a TextView to display the factorial result:
-
<TextView
android:id="@+id/textViewResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Factorial result will appear here"/>
No comments:
Post a Comment