尝试使用可变长度参数时出现类型不兼容错误

Incompatible type error when attempting to use variable length argument

我试图在我的构造函数中使用可变长度参数,但是我收到错误消息:

  1. 'Incompatible types string cannot be converted to int'

  2. 非法开始操作,';'预计

    public class Personnel {
    
    private String pname;
    private String rank;
    private String certs [];
    
    public static int totalPersonnel = 0;
    
    public Personnel(String name, String rank, String... certs) {
    
        this.pname = name;
        this.rank = rank;
        this.certs =  certs;
    
        incrPersonnel();
    
    }
    
    public static void incrPersonnel(){
        totalPersonnel++;
    }
    
    public static void main(String myArgs[]){
        Personnel Alex = new Personnel ("Alex", "CPT", ["none"] );
    

    }

    }

如果您尝试传递数组,那么您使用的方式不正确,您必须使用 new String[]{"none"},因此您的代码应如下所示:

public static void main(String myArgs[]) {
    Personnel Alex = new Personnel("Alex", "CPT", new String[]{"none"});  
}

或者您也可以使用:

public static void main(String myArgs[]) {
    Personnel Alex = new Personnel("Alex", "CPT", "val1", "val2", "val3");
    //--------------------------------------------[_____________________]
}

但在你的情况下你只传递一个值,所以你不必使用 new String[]{..},你只需要像这样传递它:

Personnel Alex = new Personnel("Alex", "CPT", "none");

如果你不想传递任何值,那么你不需要指定它你可以只传递第一个和第二个值,如:

Personnel Alex = new Personnel("Alex", "CPT");
//------------------------------------------^____no need to pass

它将return empty 用于数组