Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/386.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 - Fatal编程技术网

Java 使用另一个类的构造函数向数组列表中添加值,错误消息

Java 使用另一个类的构造函数向数组列表中添加值,错误消息,java,Java,我得到一个错误,说找不到符号,它指的是卡上面的粗体区域。addnew CardSuit.SPADES,I 我在“card”类中有以下构造函数: Card(Suit suit, int rank) { this.suit = suit; this.rank = rank; } 我在该类中声明了一些枚举: public enum Suit { SPADES, HEARTS, CLUBS,DIAMONDS } deck类是我添加到ArrayList的位置 ArrayLi

我得到一个错误,说找不到符号,它指的是卡上面的粗体区域。addnew CardSuit.SPADES,I

我在“card”类中有以下构造函数:

Card(Suit suit, int rank) {
    this.suit = suit;
    this.rank = rank; 
}
我在该类中声明了一些枚举:

public enum Suit {
    SPADES, HEARTS, CLUBS,DIAMONDS 
}
deck类是我添加到ArrayList的位置

ArrayList cards = new ArrayList(52);
Deck() {
    //ArrayList cards = new ArrayList(52);
    for (int i=0; i<=13; i++){  
    cards.add(new Card(Suit.SPADES,i));
    }
}

Suit似乎嵌套在Card类中,因此在Card类之外,您需要使用Card.Suit.SPADES或其他任何东西。

根据您的描述,Suit似乎是Card中的内部枚举。代码:

public class Card {
    public enum Suit {
        //...
    }
}
最好将其移动到单独的文件中,然后正确地将其导入到Deck类中:

java

public class Card {
    //...
}
Suit.java

public enum Suit {
    //...
}
Deck.java

public class Deck {
    //...
}

您的问题是没有为构造函数指定访问修饰符

若你们的类组和卡片在不同的包中,那个么你们不能访问它的构造函数,因为默认情况下它会有一个受保护的修饰符。这意味着,不能从包的外部调用构造函数

你的代码

Card(Suit suit, int rank) {
        this.suit = suit;
        this.rank = rank;
}
相当于

protected Card(Suit suit, int rank) {
        this.suit = suit;
        this.rank = rank;
}
但是,如果您要像下面这样更改修改器

package cards;


public class Card {

    private final Suit suit;
    private final int rank;

    public Card(Suit suit, int rank) {
        this.suit = suit;
        this.rank = rank;
    }

    public enum Suit {

        SPADES, HEARTS, CLUBS, DIAMONDS
    }
}

它将开始工作

结论:不要忘记设置访问修饰符,如果没有必要,不要依赖默认值


另外,我还重新定义了您的汽车收藏,以列出卡片=新的ArrayList 52;应该这样做

你说它嵌套在卡片里是什么意思?你是说信用卡?是的。例如,公共类卡片{public enum Suit{…}…},但是上面看到的卡片是Card类中的构造函数卡片。对,但是枚举本身是在类中定义的。所以它的类型不是适合的,它是卡。适合如果我从主要方法来做这件事,我还需要使用卡吗?另外,对于我可能有的其他方法,这是不需要的,对吗?为什么要使用原始列表?您是否注意到,他没有在构造函数上指定访问修饰符?如果两个类都在不同的包中呢@如果你把它移动到一个单独的文件中,然后将它正确地导入到你的Deck类中会更好。我也会这样做,但他的问题是,他不能访问Deck中的Card构造函数,因为它们可能在不同的包中。若整个类的修饰符也是默认的,那个么你们就知道它会导致..@T.G,这是因为OP声明了一张带有默认作用域的卡片。OP应该声明公共构造函数。
package dectks;

import cards.Card;
import cards.Card.Suit;
import java.util.ArrayList;
import java.util.List;

public class Deck {

    List<Card> cards = new ArrayList<>(52);

    Deck() {
        for (int i = 0; i <= 13; i++) {
            cards.add(new Card(Suit.SPADES, i));
        }
    }

    public static void main(String[] args) {
        Deck deck = new Deck();
    }
}