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

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

المطلوب

قم بتعريف دالة إسمها CountOccurrences, عند استدعاءها نمرر لها نصيّن, فترجع عدد صحيح يمثل كم مرة النص الثاني مكرر في النص الأول.
بعدها قم بتجربة هذه الدالة في البرنامج مع جعل المستخدم هو من يدخل النصيّن.

مثال: إذا قمنا باستخدام الدالة CountOccurrences() لمعرفة كم مرة تكررت الكلمة cat في النص I like cats. I have one cat called Lola فإنها سترجع الرقم 2.


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

import java.util.Scanner;
public class Main {
public static int CountOccurrences(String s1, String s2) {
int counter = 0;
for (int i = 0; i < s1.length() - s2.length() + 1; i++)
{
if (s1.substring(i, i + s2.length()).equals(s2))
{
counter++;
}
}
return counter;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter any text: ");
String text = input.nextLine();
System.out.print("Enter word to search occurrences: ");
String keyword = input.next();
int result = CountOccurrences(text, keyword);
System.out.println("Total occurrences of '" + keyword + "' is: " + result);
}
}
import java.util.Scanner; public class Main { public static int CountOccurrences(String s1, String s2) { int counter = 0; for (int i = 0; i < s1.length() - s2.length() + 1; i++) { if (s1.substring(i, i + s2.length()).equals(s2)) { counter++; } } return counter; } public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter any text: "); String text = input.nextLine(); System.out.print("Enter word to search occurrences: "); String keyword = input.next(); int result = CountOccurrences(text, keyword); System.out.println("Total occurrences of '" + keyword + "' is: " + result); } }

سنحصل على النتيجة التالية في حال تم إدخال نفس القيم التي تم تعليمها باللون الأصفر عند التشغيل.

Enter any text: I like cats. I have one cat called Lola
Enter word to search occurrences: cat
Total occurrences of 'cat' is: 2