简体   繁体   English

需要帮助在 object 中运行 if 语句以更改对象属性 (JAVA)

[英]Need help to run an if statement inside an object to change that objects attributes (JAVA)

Im not extremely high level at this and this is my first time really working with objects and classes.我在这方面的水平不是很高,这是我第一次真正使用对象和类。 I am trying to make a card game and want to color the card's suit name either red or black with the Java color code things.我正在尝试制作纸牌游戏,并希望使用 Java 颜色代码将卡片的套装名称着色为红色或黑色。 Each card is its own object, with a suit and a number value.每张牌都是自己的 object,有花色和数值。 Heres the "Card" class:这是“卡”class:

        public class Card {
String suit = Main.generateCardSuit();
int value = Main.generateCardValue();

**if(suit.equals("Spades") || suit.equals("Clubs")){
    String cardColor = Colors.WHITE;
} else {
    String cardColor = Colors.RED;
}**

String cardDisplay = value + ", "+ cardColor + suit + Colors.RESET;}

the methods in the Main class that determine the suit and values: Main class 中确定花色和值的方法:

` public static String generateCardSuit() {
        String cardSuit = "0";
        int suitDeterminer = (int) Math.ceil(Math.random() * 4);
        switch (suitDeterminer) {
            case 1:
                cardSuit = "Spades";
                break;
            case 2:
                cardSuit = "Clubs";
                break;
            case 3:
                cardSuit = "Hearts";
                break;
            case 4:
                cardSuit = "Diamonds";
                break;
        }
        return cardSuit;
    }

    public static int generateCardValue() {
        int gameValue = (int) Math.ceil(Math.random() * 13+1);
        return gameValue;
    }`

How the Card class is used: class卡的使用方法:

   public static void printUserHand(ArrayList < Card > userHand) {
    for (int i = 0; i < userHand.size(); i++) {
        System.out.println(i + ": " + userHand.get(i).cardDisplay);
    }
}


public static void main(String[] args) {
    ArrayList < Card > userHand = new ArrayList < Card > ();
    for (int i = 0; i < 7; i++) {
        userHand.add(new Card());
    }
    for (int i = 7; i > 0; i--) {
        Card gameCard = new Card();
        System.out.println("The dealer turns up a: " + gameCard.cardDisplay + "\n");

... ...

So i need each cards color to be an attribute, but the bolded IF statement I have in the object doesnt work.所以我需要每张卡片的颜色都是一个属性,但是我在 object 中的粗体 IF 语句不起作用。 Based on how my code is working, I dont know of a way that it could go in the Main class without causing a lot of other problems.根据我的代码的工作方式,我不知道有什么方法可以在 Main class 中 go 而不会引起很多其他问题。

Your Card class has a severe problem: it is not a class at all, it tries to execute code outside a method.你的Card class 有一个严重的问题:它根本不是 class,它试图在方法之外执行代码。

Give it a private field called cardDisplay and initialize it in a constructor of Card .给它一个名为cardDisplay的私有字段,并在Card的构造函数中对其进行初始化。 Add a method to retrieve the value of cardDisplay:添加一个方法来检索 cardDisplay 的值:

private final String cardDisplay;

public Card() {
  // put all the code from your version of Card here
  this.cardDisplay = cardDisplay;
}

public String getCardDisplay() {
  return cardDisplay;
}

If you skip the declaration in your code (that's where you specify the type of the local variable), you can even save a line with如果您跳过代码中的声明(这是您指定局部变量类型的地方),您甚至可以保存一行

  cardDisplay = value + ", "+ cardColor + suit + Colors.RESET;

Just don't skip the declaration for real local variables that are not available as fields, like probably cardColor .只是不要跳过不可用作字段的真实局部变量的声明,例如cardColor

There is a data type named Color, you might want to try setting Color cardColor = Color.yourColor and then using this value directly as your color with cardColor.有一个名为 Color 的数据类型,您可能想尝试设置Color cardColor = Color.yourColor然后直接使用此值作为 cardColor 的颜色。

EDIT to include solution:编辑以包含解决方案:

if(suit.equals("Spades") || suit.equals("Clubs")){
    Color cardColor = Colors.WHITE;
} else {
    Color cardColor = Colors.RED;
}

You might want to give this list a look, lot of other ressources there if you are starting out:https://docs.oracle.com/javase/7/docs/api/overview-summary.html您可能想看看这个列表,如果您刚开始,那里还有很多其他资源:https://docs.oracle.com/javase/7/docs/api/overview-summary.html

You mentioned it was this code that wasn't working:您提到这是无效的代码:

**if(suit.equals("Spades") || suit.equals("Clubs")){
    String cardColor = Colors.WHITE;
} else {
    String cardColor = Colors.RED;
}**

This code is creating a variable called color inside each block, but then the variable is discarded without anything being done with it.此代码在每个块内创建一个名为color的变量,但随后该变量未做任何处理就被丢弃。 If your program compiles, even though you have the code:如果您的程序可以编译,即使您有以下代码:

String cardDisplay = value + ", "+ cardColor + suit + Colors.RESET;

Then it means the variable called cardColor that that line is accessing is not the variable you assigned a color to conditionally in the code with the if statement.那么这意味着该行正在访问的名为cardColor的变量不是您在代码中使用 if 语句有条件地分配颜色的变量。 The solution to the problem you're encountering right now is to identify what variable called cardColor is being accessed on the line with String cardDisplay = and ensure that that variable is the one being modified depending on the suit in your if statement blocks.您现在遇到的问题的解决方案是确定正在使用String cardDisplay =的行访问名为cardColor的变量,并确保该变量是根据 if 语句块中的花色被修改的变量。

You need to think more object-oriented about it:您需要考虑更多面向对象的问题:

First create some enums, I would suggest a Suit and FaceValue enum:首先创建一些枚举,我建议使用 Suit 和 FaceValue 枚举:

public enum Suit {
SPADE(Color.BLACK, "Spades"),
CLUB(Color.BLACK, "Clubs"),
HEART(Color.RED, "Hearts"),
DIAMOND(Color.RED, "Diamonds");

private Color color;
private String displayValue;

public Color getColor() {
    return color;
}

private Suit(Color color, String displayValue) {
    this.color = color;
    this.displayValue = displayValue;
}

public String toString() {
    return displayValue;
}
}

public enum FaceValue {
TWO("2"),
THREE("3"),
FOUR("4"),
FIVE("5"),
SIX("6"),
SEVEN("7"),
EIGHT("8"),
NINE("9"),
TEN("10"),
JACK("J"),
QUEEN("Q"),
KING("K"),
ACE("A");

private String displayValue;

private FaceValue(String displayValue) {
    this.displayValue = displayValue;
}

public String toString() {
    return displayValue;
}
}

Then a card class:然后一张卡class:

public class Card {
private Suit suit;
private FaceValue value;

public Card(Suit suit, FaceValue value) {
    this.suit = suit;
    this.value = value;
}

public Suit getSuit() {
    return suit;
}

public FaceValue getValue() {
    return value;
}

public String toString() {
    return value + " of " + suit; 
}
}

Then you can create a deck class with basic functionality.然后你可以创建一个具有基本功能的牌组 class。

public class Deck {
private List<Card> cards = new LinkedList<Card>();

public Deck() {
    init();
    shuffle();
}

public void init() {
    cards.clear();
    for (Suit suit : Suit.values()) {
        for (FaceValue faceValue : FaceValue.values()) {
            cards.add(new Card(suit, faceValue));
        }
    }
}

public void shuffle() {
    Collections.shuffle(cards);
}

public Card drawCard() {
    return cards.remove(0);
}

public boolean hasCards() {
    return !cards.isEmpty();
}
public static void main(String [] args) {
    Deck deck = new Deck();
    while (deck.hasCards()) {
        System.out.println(deck.drawCard());
    }
}
}

From there you can create games and such.从那里您可以创建游戏等。 A player could have a Hand of Cards.玩家可能有一张手牌。 Then it's all just a matter of adding rules.然后这只是添加规则的问题。

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

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