【问题标题】:Incompatible type error when attempting to use variable length argument尝试使用可变长度参数时出现不兼容的类型错误
【发布时间】:2017-07-28 04:43:25
【问题描述】:

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

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

    }

    }

【问题讨论】:

  • 这是什么语法:` ["none"]`
  • 去掉["none"]的括号
  • 我本来打算让它成为一个空的占位符。谢谢,我现在看到了问题,这是一个疏忽!

标签: java variable-length


【解决方案1】:

如果你尝试传递一个数组,那么你使用的方式是不正确的,你必须使用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

【讨论】:

  • 或者只是字符串,因为它是可变参数
  • 感谢您的全面解释,我很感激。当我发布我的问题时,我不太了解可变长度参数的用法。
  • 我不确定你的最后一句话,数组真的为空吗?还是空的
  • 哎呀,这是正确的@Lino,它是空的,不是空的,我的错,非常感谢:)
猜你喜欢
  • 2019-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-26
  • 2019-05-07
  • 1970-01-01
  • 2020-08-15
  • 2022-01-26
相关资源
最近更新 更多