Java 程序将方法调用作为参数传递给另一个方法

javaobject oriented programmingprogramming更新于 2024/4/15 16:12:17

在本文中,我们将了解如何将方法调用作为参数传递给另一个方法。我们只需在另一个类中创建该类的对象即可从另一个类调用方法。创建对象后,使用对象引用变量调用方法。

下面是相同的演示 −

输入

假设我们的输入是 −

输入两个数字:2 和 3

输出

所需的输出将是 −

两个数字之和的立方是:
125

算法

步骤 1 - 开始
步骤 2 - 声明两个变量值,即 my_input_1 和 my_input_2
步骤 3 - 我们定义一个函数,它接受两个数字并返回它们的和。
步骤 4 - 我们定义另一个函数,它接受一个参数并将其乘以三倍,并返回输出。
步骤 5 - 在主函数中,我们创建该类的一个新对象,并创建一个 Scanner 对象。
步骤 6 - 现在,我们可以预先定义数字或提示用户输入数字。
步骤 7 - 输入完成后,我们将调用返回输入立方体的函数。
步骤 8 - 此结果显示在控制台上。

示例 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));
   }
}

输出

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));
   }
}

输出

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

相关文章


有用资源