activity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/inputNumberEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter a number"
android:inputType="number" />
<Button
android:id="@+id/checkPrimeButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/inputNumberEditText"
android:layout_marginTop="16dp"
android:text="Check Prime" />
<TextView
android:id="@+id/resultTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/checkPrimeButton"
android:layout_marginTop="16dp"
android:text="" />
</RelativeLayout>
activity.java
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
private EditText inputNumberEditText;
private Button checkPrimeButton;
private TextView resultTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inputNumberEditText = findViewById(R.id.inputNumberEditText);
checkPrimeButton = findViewById(R.id.checkPrimeButton);
resultTextView = findViewById(R.id.resultTextView);
checkPrimeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
checkPrime();
}
});
}
private void checkPrime() {
String inputNumberStr = inputNumberEditText.getText().toString().trim();
if (!inputNumberStr.isEmpty()) {
int number = Integer.parseInt(inputNumberStr);
boolean isPrime = isPrime(number);
if (isPrime) {
resultTextView.setText(number + " is a prime number.");
} else {
resultTextView.setText(number + " is not a prime number.");
}
} else {
resultTextView.setText("Please enter a number.");
}
}
private boolean isPrime(int number) {
if (number <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(number); i++) {
if (number % i == 0) {
return false; // Found a divisor, not a prime number
}
}
return true; // No divisors found, it's a prime number
}
}