繁体   English   中英

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

[英]Incompatible type error when attempting to use variable length argument

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

  1. '不兼容的类型字符串不能转换为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

它将为该数组返回empty

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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