Programming Basics SQL HTML CSS JavaScript Python C++ Java JavaFX Swing Problem Solving English English Conversations Computer Fundamentals Learn Typing

تحديات برمجيةالتحدي الثالث - حل التمرين الأول بلغة جافا

المطلوب

قم بتعريف دالة إسمها CountWords, عند استدعاءها نمرر لها نص, فترجع عدد الكلمات الموجودة في هذا النص.
بعدها قم بتجربة هذه الدالة في البرنامج.

مثال: إذا قمنا باستخدام الدالة CountWords() و تمرير النص "Programming is easy to learn." فإنها سترجع الرقم 5.


الحل بلغة جافا

public class Main {
public static void main(String[] args) {
String text = "Programming is easy to learn.";
int numberOfWords = countWords(text);
System.out.println("Total words: " + numberOfWords);
}
public static int countWords(String s) {
if (s == null || s.isEmpty()) {
return 0;
}
int counter = s.split(" ").length;
return counter;
}
}
public class Main { public static void main(String[] args) { String text = "Programming is easy to learn."; int numberOfWords = countWords(text); System.out.println("Total words: " + numberOfWords); } public static int countWords(String s) { if (s == null || s.isEmpty()) { return 0; } int counter = s.split(" ").length; return counter; } }

سنحصل على النتيجة التالية عند التشغيل.

Total words: 5
		

الدورات

أدوات مساعدة

أقسام الموقع

دورات
مقالات كتب مشاريع أسئلة