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

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

المطلوب

أكتب برنامج يطلب من المستخدم إدخال أي رقم يريد للبحث عنه بداخل مصفوفة أرقام أحادية (ذات بعد واحد) جاهزة.
بعدها سيقوم البرنامج بطباعة كم مرة تم إيجاد الرقم الذي أدخله المستخدم في المصفوفة.


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

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int array[] = {1, 2, 5, 3, 2, 4, 7, 2};
int found = 0;
int x;
System.out.print("Enter a number: ");
x = input.nextInt();
for (int i = 0; i < array.length; i++)
{
if (array[i] == x)
{
found++;
}
}
if(found == 1)
{
System.out.println("'" + x + "' is found 1 time");
}
else if(found > 1)
{
System.out.println("'" + x + "' is found " + found + " times");
}
else
{
System.out.println("'" + x + "' is not found");
}
}
}
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); int array[] = {1, 2, 5, 3, 2, 4, 7, 2}; int found = 0; int x; System.out.print("Enter a number: "); x = input.nextInt(); for (int i = 0; i < array.length; i++) { if (array[i] == x) { found++; } } if(found == 1) { System.out.println("'" + x + "' is found 1 time"); } else if(found > 1) { System.out.println("'" + x + "' is found " + found + " times"); } else { System.out.println("'" + x + "' is not found"); } } }

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

Enter a number: 2
'2' is found 3 times