將方法呼叫作為引數傳遞到另一個方法的 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