Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

โปรแกรม Java ส่งการเรียกเมธอดเป็นอาร์กิวเมนต์ (Method Call as Argument)


ในบทความนี้ เราจะทำความเข้าใจวิธี ส่งการเรียกเมธอดหนึ่งเป็นอาร์กิวเมนต์ของอีกเมธอดหนึ่ง (Pass Method Call as Argument) ใน Java

หลักการ: เรียกเมธอด A ได้ค่ากลับมา → ส่งค่านั้นเข้าเมธอด B ทันที โดยไม่ต้องเก็บในตัวแปรกลาง

ตัวอย่าง Input และ Output

Input:

Enter two numbers : 2 and 3

Output:

The cube of the sum of two numbers is: 125

(เพราะ (2+3)³ = 5³ = 125)

อัลกอริธึม

ขั้นตอนที่ 1 - เริ่มต้น
ขั้นตอนที่ 2 - ประกาศตัวแปร my_input_1, my_input_2
ขั้นตอนที่ 3 - สร้างฟังก์ชัน my_sum รับ 2 ตัวเลข คืนค่าผลบวก
ขั้นตอนที่ 4 - สร้างฟังก์ชัน my_cube รับ 1 ตัวเลข คำนวณยกกำลัง 3 แล้วพิมพ์
ขั้นตอนที่ 5 - ใน main สร้างออบเจกต์ รับค่าจากผู้ใช้
ขั้นตอนที่ 6 - เรียก obj.my_cube(obj.my_sum(my_input_1, my_input_2)) ส่งผลลัพธ์ทันที
ขั้นตอนที่ 7 - แสดงผลลัพธ์

ตัวอย่างที่ 1: รับค่าจากผู้ใช้

import java.util.Scanner;
public class Main {
    public int my_sum(int a, int b) {
        int sum = a + b;
        return sum;
    }
    public void my_cube(int my_input) {
        int my_result = my_input * my_input * my_input;
        System.out.println(my_result);
    }
    public static void main(String[] args) {
        Main obj = new Main();
        int my_input_1, my_input_2;
        System.out.println("Required packages have been imported");
        Scanner my_scanner = new Scanner(System.in);
        System.out.println("A reader object has been defined");
        System.out.print("Enter the first number : ");
        my_input_1 = my_scanner.nextInt();
        System.out.print("Enter the second number : ");
        my_input_2 = my_scanner.nextInt();
        System.out.println("The cube of the sum of two numbers is: ");
        obj.my_cube(obj.my_sum(my_input_1, my_input_2));
    }
}

Output

Required packages have been imported
A reader object has been defined
Enter the first number : 2
Enter the second number : 3
The cube of the sum of two numbers is: 125

ตัวอย่างที่ 2: กำหนดค่าไว้ล่วงหน้า

public class Main {
    public int my_sum(int a, int b) {
        int sum = a + b;
        return sum;
    }
    public void my_cube(int my_input) {
        int my_result = my_input * my_input * my_input;
        System.out.println(my_result);
    }
    public static void main(String[] args) {
        Main obj = new Main();
        int my_input_1, my_input_2;
        my_input_1 = 3;
        my_input_2 = 2;
        System.out.println("The two number is defined as " + my_input_1 + " and " + my_input_2);
        System.out.println("The cube of the sum of two numbers is: ");
        obj.my_cube(obj.my_sum(my_input_1, my_input_2));
    }
}

Output

The two number is defined as 3 and 2
The cube of the sum of two numbers is: 125