تحديات برمجيةالتحدي الثالث - حل التمرين الخامس بلغة جافا
المطلوب
قم بإنشاء برنامج يطلب من المستخدم إدخال نصّين, بعدها يقوم بطباعة ما إن كان النص الأول ينتهي بالنص الثاني أم لا.
مثال
Enter text 1: Welcome to my world Enter text 2: world -------------------------------- Text 1 is end with 'world'
الحل بلغة جافا
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String text1, text2;
int text2Counter = 0;
boolean found = true;
System.out.print("Enter text 1: ");
text1 = input.nextLine();
System.out.print("Enter text 2: ");
text2 = input.nextLine();
for (int i = text1.length() - text2.length(); i < text1.length() && found == true; i++)
{
if(text1.charAt(i) != text2.charAt(text2Counter))
{
found = false;
}
text2Counter++;
}
System.out.println("--------------------------------");
if(found)
{
System.out.println("Text 1 end with '" + text2 + "'");
}
else
{
System.out.println("Text 1 is not end with '" + text2 + "'");
}
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String text1, text2;
int text2Counter = 0;
boolean found = true;
System.out.print("Enter text 1: ");
text1 = input.nextLine();
System.out.print("Enter text 2: ");
text2 = input.nextLine();
for (int i = text1.length() - text2.length(); i < text1.length() && found == true; i++)
{
if(text1.charAt(i) != text2.charAt(text2Counter))
{
found = false;
}
text2Counter++;
}
System.out.println("--------------------------------");
if(found)
{
System.out.println("Text 1 end with '" + text2 + "'");
}
else
{
System.out.println("Text 1 is not end with '" + text2 + "'");
}
}
}
سنحصل على النتيجة التالية في حال تم إدخال نفس القيم التي تم تعليمها باللون الأصفر عند التشغيل.
Enter text 1: Welcome to my world
Enter text 2: world
--------------------------------
Text 1 is end with 'world'
Enter text 2: world
--------------------------------
Text 1 is end with 'world'