簡體   English   中英

在java中使用多個數組的構造函數

[英]Constructor using multiple arrays in java

在創建一個構造函數時遇到問題,該構造函數需要多個String的一維數組:

class relation {

String[] setA, setB, setC;

relation (String[] setA, String[] setB, String[] setC) {
    this.setA = setA;
    this.setB = setB;
    this.setC = setC;
} 
}

public class matrix {

public static void main(String[] args) {

    relation relation1 = new relation({"1","2","3","4","5"}, {"1","2","3","4"}, {"2","3","4","5"});
    relation relation2 = new relation({"a","b","c","d"}, {"a","b","c","d","b","c"}, {"a","b","c","d","c","b"});

}

}

我不斷收到多個錯誤 - 令牌上的語法錯誤,錯位的構造(s) - 類型不匹配:無法從String []轉換為關系 - 令牌“}”上的語法錯誤,刪除此令牌 - 令牌上的語法錯誤“) “,}期待

我需要能夠使用關系類分別使用每個數組。

您不能在Java中使用這種方式的數組文字 - 您必須顯式初始化它們。 例如:

relation relation1 = new relation(new String[]{"1","2","3","4","5"}, 
                                  new String[]{"1","2","3","4"},
                                  new String[]{"2","3","4","5"});

你可以這樣做 -

class Relation {
    String[] setA, setB, setC;
    Relation(String[] setA, String[] setB, String[] setC) {
        this.setA = setA;
        this.setB = setB;
        this.setC = setC;
    }
}

public class Assignment3 {

    public static void main(String[] args) {
        Relation relation1 = new Relation(
                new String[]{"1", "2", "3", "4", "5"}, new String[]{"1", "2",
                        "3", "4"}, new String[]{"2", "3", "4", "5"});
        Relation relation2 = new Relation(new String[]{"a", "b", "c", "d"},
                new String[]{"a", "b", "c", "d", "b", "c"}, new String[]{"a",
                        "b", "c", "d", "c", "b"});
    }
}

嘗試這樣它會起作用

relation relation1 = new relation(new String[]{"1","2","3","4","5"},
                        new String[]{"1","2","3","4"},new String[]{"2","3","4","5"});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM