将方法调用作为参数传递到另一个方法的 Java 程序
在本文中,我们将了解如何将方法调用作为参数传递到另一个方法。我们可以通过简单地 创建另一个类中的对象,从另一个类中调用方法。创建对象后,使用对象引用变量调用方法。
以下是相同的演示 −
输入
假设我们的输入如下 −
Enter two numbers : 2 and 3
输出
所需的输出如下 −
The cube of the sum of two numbers is: 125
算法
Step 1 - START Step 2 - Declare two variables values namely my_input_1 and my_input_2 Step 3 - We define a function that takes two numbers, and returns their sum. Step 4 - We define another function that takes one argument and multiplies it thrice, and returns the output. Step 5 - In the main function, we create a new object of the class, and create a Scanner object. Step 6 - Now, we can either pre-define the number or prompt the user to enter it. Step 7 - Once we have the inputs in place, we invoke the function that returns the cube of the input. Step 8 - This result is displayed on the console.
示例 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP