كل المقررات

الرئيسية / مقرر تطبيقات الموبايل / الفصل 6 الجزء 1

الفصل 6 (الجزء 1): Java methods

Structure, signature, parameters and scope

على طول: شكل الدالة، وتوقيعها، وإزاي بتأثر على المتغيرات.

فيديو المحاضرة

فيديو المحاضرة

بعد الفيديو: الأمثلة والاختبار والتمارين والمشروع الصغير تحت.

رسوم متحركة

المنادي والدالة

أمثلة كود

أمثلة قصيرة وبسيطة

كل مثال وراه زرار «شغّل خطوة بخطوة»: بيعلّم على السطر اللي بيتنفّذ ويطبع الناتج زي ما بيتنفّذ بالظبط. ده شرح تنفيذ الكود سطر بسطر، مش مترجم حقيقي جوه الصفحة.

المثال ١: دالة بحساب وطباعة

public static int add(int a, int b) {    return a + b;}int x = add(3, 4);System.out.println(x);

    

المثال ٢: القيمة بتتبعت بالنسخة

static void bump(int n) {    n = n + 1;    System.out.println("inside: " + n);}int count = 5;bump(count);System.out.println("outside: " + count);

    

المثال ٣: الـ scope

int total = 0;for (int i = 1; i <= 3; i++) {    int step = i * 2;    total += step;}System.out.println(total);System.out.println(step);   // step does not exist here

    

اختبار قصير

اختبر فهمك

1. A method signature is:

2. Java passes arguments:

3. A local variable is visible:

4. Which is a predefined method?

5. A method declared int must:

تمارين

جرّب بإيدك

التمرين 1

اكتب دالة max بترجّع الأكبر من رقمين، واطبع max(12, 30).

Write a max method returning the larger of two numbers, and print max(12, 30).

Starter code:

// TODO: max method and one println

التمرين 2

اكتب دالة greet بتاخد اسم وبترجّع نص ترحيب، واطبعها لاسم Mona.

Write a greet method that takes a name and returns a greeting, and print it for Mona.

Starter code:

// TODO: greet method returning "Hello, " + name

مشروع صغير في آخر المحاضرة

حاسبة بثلاث دوال

الداتا: calc: our own two numbers (12 and 5), no user data.

License / source: Our own code; Oracle methods tutorial link only. Reference page

الخطوات

  1. اكتب تلات دوال: add وsub وmax، كل واحدة بتاخد رقمين.
  2. نادي التلاتة على 12 و 5.
  3. اطبع كل ناتج في سطر بالشكل: add = 17.
  4. المتوقع تحت.

Starter code:

// TODO: add, sub, max// TODO: three println lines

Credits: the topic order follows the course notes "Mobile Application Development 1" by Dr. Muhammad Kashif Saeed (Applied College, Muhayil, King Khalid University), shared by the course owner. The explanations, diagrams, data and code in this lecture are our own; we copy nothing from the notes. Extra reference: Oracle Java tutorials: defining methods, constructors, overloading and recursion (docs.oracle.com/javase/tutorial).