从构造函数Java获取特定参数

时间:2020-07-12 05:17:17

标签: java arraylist

我正在使用纸牌中的纸牌作为积分来创建一个简单的游戏。到目前为止,我已经创建了纸牌并成功打印。该程序包含两个类,游戏(包含主要方法)和(创建卡)。我正在尝试创建一种方法(该方法称为 Points ),该方法返回每张卡的总数,但是我不知道如何从对象的其余部分提取卡的值。是否有某种eck.something可以提取该特定参数?

如果已经回答了这个问题,那么如果您可以将我指向该问题,将不胜感激。

下面是我作品的简化版本。

Card.java

class Card {
  private final String name;
  private final Integer value;

  Card (String name, int value) {
    this.name = name;
    this.value = value;
  }

  public String getName () { return name; }
  public String getValue () { return value; }

  public String toString() { return (this.name + " = " + this.value); }
}

Game.java

public class Game {
  public static void createDeck (ArrayList<Card> deck) {
    for (int i = 0; i < 10; i ++) { //creates cards 0 - 10
      Card obj = new Card("Card", i);
      deck.add(obj);
    }

  public static Int Points (ArrayList<Card> deck) {} //should return 81 = 0 + 1 + 2 + 3 + ...

  public static void main (String [] args) {
    ArrayList<Card> deck = new ArrayList<Card>();
    createDeck(deck);
    Points(deck);
}

2 个答案:

答案 0 :(得分:0)

卡类中有一个问题。 getValue的返回类型应该是Integer而不是String

public String getValue () { return value; }

应该是

public Integer getValue () { return value; }

这是编写点方法的方法:

public static Integer points (ArrayList<Card> deck) {
        Integer total =0;
        for (int i = 0; i < deck.size();i++) { 
          total+=deck.get(i).getValue();
        }
    return total;
}

答案 1 :(得分:0)

private class Card{
    private Integer value;
    private String name;
    
    public Card(Integer value, String name) {
        this.value = value;
        this.name = name;
    }

    Integer getValue() {
        return this.value;
    }
}

public static int points(ArrayList<Card> cards) {
    return cards.stream().mapToInt(c -> c.getValue()).sum();
}