繁体   English   中英

如何将变量从一个参数化方法传递到另一个?

[英]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");

或者您可以只传递AB所需的所有参数:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM