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 n;
do {
System.out.print("Enter the number of lines: ");
n = input.nextInt();
}
while (n <= 0);
if (n % 2 == 0)
{
n++;
}
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
if (i == j || j == n - i + 1) {
System.out.print("*");
}
else {
System.out.print(" ");
}
}
System.out.println();
}
}
}
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n; do { System.out.print("Enter the number of lines: "); n = input.nextInt(); } while (n <= 0); if (n % 2 == 0) { n++; } for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { if (i == j || j == n - i + 1) { System.out.print("*"); } else { System.out.print(" "); } } System.out.println(); } } }

سنحصل على النتيجة التالية إذا قام المستخدم بإدخال الرقم 9 عند التشغيل.

Enter the number of lines: 9
*       *
 *     * 
  *   *  
   * *   
    *    
   * *   
  *   *  
 *     * 
*       *