المطلوب
قم بتعريف دالة إسمها PrintWordsOccurence, نمرر لها نص عند إستدعاءها فتقوم بطباعة كم مرة تكررت كل كلمة في هذا النص.
مثال: إذا قمنا باستخدام الدالة PrintWordsOccurence() و تمرير النص "I am happy. I am a doctor. I like chocolate." فإنها ستطبع النتيجة التالية.
[3] I [2] am [1] happy. [1] a [1] doctor. [1] like [1] chocolate.
الحل بلغة جافا
public class Main {
public static void main(String[] args) {
String text = "I am happy. I am a doctor. I like chocolate.";
printWordsOccurence(text);
}
public static void printWordsOccurence(String s) {
if (s == null || s.isEmpty())
{
System.out.println("There is no text!");
return;
}
String[] words = s.split(" ");
int counter;
for (int i = 0; i < words.length; i++)
{
counter = 1;
for (int j = i + 1; j < words.length; j++)
{
if (words[i].equals(words[j]))
{
counter = counter + 1;
words[j] = "";
}
}
if (!words[i].equals(""))
{
System.out.println("[" + counter + "] " + words[i]);
}
}
}
}
سنحصل على النتيجة التالية عند التشغيل.
[3] I [2] am [1] happy. [1] a [1] doctor. [1] like [1] chocolate.


محرر الويب
نظام الألوان
محول الوحدات
محلل عناوين الشبكات