تدريب عملي
التدريب العملي 34: الدوال النصية
من مذكرة العملي. اقرأ المسألة والخوارزمية، ثم اكتب البرنامج ونفّذه.
من الدرس 9. الدوال · كل التدريبات
١نص المسألة
أكتب نص البرنامج التالي. تعرف على عمل الدوال النصية
٢الخوارزمية
خوارزمية مقترحة.
- ابدأ
- خزّن اسم الطالب في متغير نصي
- اطبع طول النص، ثم النص بالأحرف الكبيرة ثم الصغيرة
- ابحث عن مواضع بعض الأحرف بالدالة indexOf
- اقتطع أول أربعة أحرف بالدالة substring
- اربط نصين بالرمز + ثم بالدالة concat
- قارن بين نصين بالدالتين compareTo و equals
- تحقق من احتواء النص على أحرف معيّنة بالدالة contains
- توقف
٣خطوات التطبيق
- أنشئ مشروعًا جديدًا في NetBeans: File ← New Project ← Java with Ant ← Java Application، باسم lab34.
- اكتب الكود داخل الدالة main، ثم شغّله بالزر Run أو F6.
٤المخرجات المطلوبة
نفّذ برنامجك، ويجب أن تظهر المخرجات التالية:
run:
Rami Ali Alfahad
Length: 16
RAMI ALI ALFAHAD
rami ali alfahad
Index of 'Rami': 0
Index of ' ': 4
Index of 'i': 3
أول أربعة أحرف من اسم الطالب
Rami
ربط قيمتين نصية باستخدام رمز الجمع
Yasser Ali
ربط قيمتين نصية باستخدام دالة الدمج
YasserAli
Rami Ali "Rami" Alfahad
student id Student name
10 + 20 = 30
1020
هل هما متساوييان في القيمة
0
true
التحقق إذا كان المتغير يحتوي على سلسلة من الأحرف
true
true
false
BUILD SUCCESSFUL (total time: 0 seconds)
٥الحل المقترح
حاول بنفسك أولًا، ثم قارن حلّك بالحل التالي:
👁 اعرض الحل المقترح
public class Lab34 { public static void main(String[] args) { String stdname = "Rami Ali Alfahad"; System.out.println(stdname); System.out.println("Length: " + stdname.length()); System.out.println(stdname.toUpperCase()); System.out.println(stdname.toLowerCase()); System.out.print("Index of 'Rami': "); System.out.println(stdname.indexOf("Rami")); System.out.print("Index of ' ': "); System.out.println(stdname.indexOf(" ")); System.out.print("Index of 'i': "); System.out.println(stdname.indexOf("i")); System.out.println("أول أربعة أحرف من اسم الطالب"); System.out.println(stdname.substring(0, 4)); // Rami String firstName = "Yasser"; String lastName = "Ali"; System.out.println("ربط قيمتين نصية باستخدام رمز الجمع"); System.out.println(firstName + " " + lastName); System.out.println("ربط قيمتين نصية باستخدام دالة الدمج"); System.out.println(firstName.concat(lastName)); String txt = "Rami Ali \"Rami\" Alfahad"; System.out.println(txt); String txt2 = "student id\tStudent name"; System.out.println(txt2); int x = 10; int y = 20; int z = x + y; System.out.print(x + " + " + y + " = "); System.out.println(z); // output 30 String a = "10"; String b = a + y; System.out.println(b); // output 1020 String n1 = "Rami"; String n2 = "Rami"; System.out.println("هل هما متساوييان في القيمة"); System.out.println(n1.compareTo(n2)); System.out.println(n1.equals(n2)); System.out.println("التحقق إذا كان المتغير يحتوي على سلسلة من الأحرف"); System.out.println(n1.contains("Ra")); // true System.out.println(n1.contains("i")); // true System.out.println(n1.contains("Rm")); // false }}