[英]How to pass variable from one parameterized method to another?
如何將變量從 main 方法發送到 Method A
,以及在方法B
中我應該在A()
中傳遞什么參數。
代碼:
public class MethodCall {
public void A(String c) {
System.out.println(c);
}
public void B() {
A(); // What parameter do I pass here. method B is dependent on A
}
@Test
public void D() {
B();
MethodCall mc = new MethodCall();
mc.A("Hello");
}
}
在方法A
中,您需要一個String
類型的參數,因此您必須為String
提供一個參數,它可以只是一個空的 String ""
或null
。
另一種選擇取決於您的用例; 你可以使用可變參數:
public void a(String... varargs) {...}
在這種情況下,可以提供零個或多個String
類型的參數。 所以這有效:
a("Hello World");
這個:
a();
但也是這樣:
a("Hello", "World");
或者您可以只傳遞A
到B
所需的所有參數:
public class MethodCall {
public void A(String c) {
System.out.println(c);
}
public void B(String c) {
A(c);
}
@Test
public void D() {
MethodCall mc = new MethodCall();
mc.B("Hello World");
mc.A("Hello");
}
}
您應該在方法 B 中在 A() 中傳遞字符串參數。
public class MethodCall {
public void A(String c) {
System.out.println(c);
}
public void B() {
A("Pass the String parameter");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
MethodCall mc = new MethodCall();
mc.A("Hello");
mc.B();
}
}
當您將 String 類型作為參數傳遞時,這意味着您應該在為參數賦值時使用相同的數據類型。 您不能使用任何其他類型,如 Integer、float 等。您只需將 String 值傳遞給給定參數。
當您使用非靜態方法時,它不能直接調用。 所以使用 static 關鍵字直接調用方法。
回答-
public class MethodCall {
public static void A(String c) {
System.out.println(c);
}
public static void B() {
A("HI "); //you can put `null` or `empty`
}
public static void main(String[] args) {
B();
MethodCall mc = new MethodCall();
mc.A("Hello");
}
}
我不太確定你的問題,但這是我的看法:
public class MethodCall {
public void A(String c) {
System.out.println(c);
}
public void B(String s) {
A(s); //If you want to call A() here, then you would have to pass a variable in the parameters of A(), as A() is a parameterized method by definition.
}
public static void main(String[] args) {
// TODO Auto-generated method stub
MethodCall mc = new MethodCall();
mc.A("Hello"); //This part is right, that is how you pass value of a non static function through main method.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.