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