Create a Simple Application, which read a positive number from the user and display its factorial value in another activity.
Soln :
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/et_apti_number"
android:textStyle="bold"
android:textSize="18sp"
android:layout_margin="20dp"
android:padding="10dp"
/>
<Button
android:id="@+id/b_apti_calc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Calculate"
android:textColor="#ffffff"
android:textStyle="bold"
android:textSize="18sp"
android:layout_margin="20dp"
android:padding="10dp"/>
<TextView
android:id="@+id/tv_apti_answer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Answer"
android:textColor="#000000"
android:textStyle="bold"
android:textSize="18sp"
android:layout_margin="20dp"
android:padding="10dp"/>
</LinearLayout>
</LinearLayout>
MainActivity.java
package com.example.slipap3a;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
EditText number;
TextView answer;
Button calculate;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialize();
}
private void initialize() {
number = (EditText) findViewById(R.id.et_apti_number);
number.setHint("Enter number to be factorialized :P");
answer = (TextView) findViewById(R.id.tv_apti_answer);
calculate = (Button) findViewById(R.id.b_apti_calc);
calculate.setOnClickListener(this);
}
private long calcFactorial() {
long factorial = 1;
try {
factorial = Long.parseLong(number.getText().toString());
for (int i = (int) (factorial - 1); i > 0; i--) {
factorial = i * factorial;
Toast.makeText(this, "correct", Toast.LENGTH_LONG).show();
}
} catch (NumberFormatException e) {
Toast.makeText(this, "Incorrect Input", Toast.LENGTH_LONG).show();
} finally {
}
return factorial;
}
@Override
public void onClick(View v) {
answer.setText("Factorial of " + number.getText().toString() + " is : " + calcFactorial());
}
}
0 Comments