एंड्रॉइड में EditText इनपुट की पहली संख्या सम/विषम जांचना
यह ट्यूटोरियल दिखाता है कि उपयोगकर्ता द्वारा दर्ज संख्या का पहला अंक सम है या विषम, बटन क्लिक पर कैसे जांचें।
चरण 1: नया प्रोजेक्ट बनाएं
Android Studio में File → New Project चुनें।
चरण 2: लेआउट (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:gravity="center"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<EditText
android:id="@+id/edit_query"
android:layout_width="match_parent"
android:hint="संख्या दर्ज करें"
android:inputType="number"
android:layout_height="wrap_content" />
<Button
android:id="@+id/buttonPanel"
android:text="जांचें"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
चरण 3: MainActivity कोड (java/MainActivity.java)
package com.example.myapplication;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText editQuery = findViewById(R.id.edit_query);
findViewById(R.id.buttonPanel).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String data = editQuery.getText().toString().trim();
if (!data.isEmpty()) {
try {
// पहला कैरेक्टर लें
char firstChar = data.charAt(0);
// जांचें कि यह अंक है
if (Character.isDigit(firstChar)) {
int digit = Character.getNumericValue(firstChar);
if (digit % 2 == 0) {
Toast.makeText(MainActivity.this, digit + " सम है", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, digit + " विषम है", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(MainActivity.this, "पहला कैरेक्टर संख्या नहीं है", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Toast.makeText(MainActivity.this, "त्रुटि: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
} else {
editQuery.setError("कृपया संख्या दर्ज करें");
}
}
});
}
}
मुख्य सुधार
Character.isDigit()से वैलिडेट करें कि पहला कैरेक्टर अंक हैCharacter.getNumericValue()से सुरक्षित रूप से अंक प्राप्त करें.trim()से व्हाइटस्पेस हटाएं- त्रुटि हैंडलिंग जोड़ा गया
विस्तार विचार
- पूरी संख्या सम/विषम जांचने के लिए:
Long.parseLong(data) % 2 == 0 - रियल-टाइम वैलिडेशन के लिए
TextWatcherउपयोग करें - नकारात्मक संख्याओं और दशमलव के लिए हैंडलिंग जोड़ें
ऐप चलाएं
संख्या दर्ज करें, "जांचें" दबाएं - टोस्ट पहला अंक सम/विषम बताएगा।