Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java-不同的参数导致不同的输出_Java_Oop_Inheritance - Fatal编程技术网

Java-不同的参数导致不同的输出

Java-不同的参数导致不同的输出,java,oop,inheritance,Java,Oop,Inheritance,我希望实现以下目标: 如果我使用参数a或b调用方法v2.horn(),它应该输出a或b。但不知怎的,我不知道怎么做 代码如下: public class Vehicle { int maxSpeed; int wheels; String color; double fuelCapacity; void horn(a,b) { String a = "Beep!"; String b = "Boop!";

我希望实现以下目标:

如果我使用参数a或b调用方法v2.horn(),它应该输出a或b。但不知怎的,我不知道怎么做

代码如下:

public class Vehicle {
    int maxSpeed;
    int wheels;
    String color;
    double fuelCapacity;  

    void horn(a,b) {
        String a = "Beep!";
        String b = "Boop!";
        System.out.println(a);
        System.out.println(b);
    }

    void blink() {
        System.out.println("I'm blinking!");
    }
}

class MyClass {
    public static void main(String[ ] args) {
        Vehicle v1 = new Vehicle();
        Vehicle v2 = new Vehicle();
        v1.color = "red";
        v2.horn(a);
        v1.blink();
    }
}

我认为您试图实现的是,当您使用某些参数调用方法“horn”时,它必须使用“Beep!”或“Boop!”

第一项:

void horn(a,b)
在Java中不是有效的函数签名,在Java函数中,您必须始终指定您提供的输入是什么类型

在函数中,必须定义a和b是字符串,如下所示:

void horn(String a, String b)
如果您希望您的代码以您现在编写的方式运行,您必须稍微移动您的代码,您最终会得到以下结果:

public class Vehicle {
int maxSpeed;
int wheels;
String color;
double fuelCapacity;

void horn(String in) {
    System.out.println(in);
}

void blink() {
    System.out.println("I'm blinking!");
}
}

class MyClass {
public static void main(String[ ] args) {
    String a = "Beep!";
    String b = "Boop!"; 

    Vehicle v1 = new Vehicle();
    Vehicle v2 = new Vehicle();
    v1.color = "red";
    v2.horn(a);
    v1.blink();
    }
}
实现所需功能的另一种方法是:也可以使用布尔值

void horn(boolean a) {
    if (a)
    {
        System.out.println("Beep!");
    }
    else
    {
        System.out.println("Boop!");
    }
}   
然后,为了完成您想做的事情,您必须像这样调用该方法:

// Use either true or false.
v2.horn(true); 
v2.horn(false);

这甚至不编译?这与参数无关。您通常缺少。它是一个双参数方法,不能使用一个参数调用它。我的问题是如何输出a或b。但没有人能给我一个答案或解释?如果你以后不打算使用它,为什么还要在horn函数中传递参数?