Я не могу получить свойства определенной карты в этом коде, она всегда печатает null
и я не знаю почему. Я из мира Php-HTML, и я новичок в JAVA.
Это от Opportunity.java
package opportunity;
import java.io.*;
import java.util.Collections;
import java.util.List;
import static java.util.stream.Collectors.toList;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import opportunity.Card.CardType;
public class Opportunity {
/*Player 1 */
public int p1_money = 10000;
public int p1_card_d = 40;
public int p1_card_h = 0;
/*Player 2 */
public int p2_money = 10000;
public int p2_card_d = 40;
public int p2_card_h = 0;
/**
* @param args the command line arguments
* @throws java.io.IOException
*/
public static void main(String[] args) throws IOException {
System.out.print("***************Opportunity***************\n");
final Card card1 = new Card(Card.CardType.EVENT, "Get Tax Returns").
setProperty("cost", "0.00").
setProperty("Effect", "Effect: Earn money equal to the\n"
+ "maximum income each of your\n"
+ "properties can give you,\n"
+ "depending on their level.");
final Card card2 = new Card(Card.CardType.EVENT, "BIR Hunting Begins").
setProperty("cost", "0.00").
setProperty("Effect", "Effect: An opponent loses\n"
+ "money equal to 50% of the\n"
+ "maximum income each of\n"
+ "their properties can give him or her,\n"
+ "depending on the level of the\n"
+ "property.");
final Card card3 = new Card(Card.CardType.EVENT, "Restore Balance").
setProperty("cost", "10000.00").
setProperty("Effect", "Effect: The total income of all\n"
+ "the players becomes equal to\n"
+ "the income of the player\n"
+ "with the lowest income.");
final List<Card> deck = Stream.of(CardType.values()).
flatMap(type -> IntStream.rangeClosed(1, 4).mapToObj(num -> new Card(type, "CardName" + num))).
collect(toList());
Collections.shuffle(deck);
System.out.println(deck.get(0).getProperty("Effect"));
}
}
И это коды от Card.java
package opportunity;
import java.util.*;
public class Card {
public enum CardType {
EVENT,
PROPERTY,
ASSET;
}
private final CardType cardType;
private final String cardName;
private final Map<String, String> properties = new HashMap<>();
Card(final CardType cardType, final String cardName) {
this.cardType = cardType;
this.cardName = cardName;
}
public Card setProperty(final String name, final String value) {
properties.put(name, value);
return this;
}
public String getProperty(final String name) {
return properties.get(name);
}
}
Он всегда возвращает это:
run:
***************Opportunity***************
null
BUILD SUCCESSFUL (total time: 0 seconds)
хотя я ставлю индекс на get()
Для того, чтобы построить на @Luiggi Мендоса ответ, вы не добавляете свои объекты карты на deck
список.
замещать
final List<Card> deck = Stream.of(CardType.values()).
flatMap(type -> IntStream.rangeClosed(1, 4).mapToObj(num -> new Card(type, "CardName" + num))).
collect(toList());
С
final List<Card> deck = new ArrayList<>();
deck.add(card1);
deck.add(card2);
deck.add(card3);
Вместо добавления новых Cards
в список добавьте объекты, которые вы уже создали, и установили свойства.
Изменение: отправить комментарий
final List<Card> deck = new ArrayList<>();
for (int i=0; i<4; i++) {
deck.add(card1);
deck.add(card2);
deck.add(card3);
}
Это добавит четыре копии каждой из трех ваших карт в список.
card1
, 4 из card2
, 4 из card3
.
Вот:
final List<Card> deck = Stream.of(CardType.values()).
flatMap(type -> IntStream.rangeClosed(1, 4).mapToObj(num -> new Card(type, "CardName" + num))).
collect(toList());
Collections.shuffle(deck);
Вы заполняете List<Card> deck
новой Card
, вы не добавляете никаких других переменных cardX
. Таким образом, при получении этого свойства "Effect"
вы получаете null
потому что у Card
в deck
нет ранее установленного свойства "Effect"
.
Комментарий предыдущих людей совершенно прав. Вы не добавляете созданные карты в список.
Попробуйте заменить свой код
final List<Card> deck = Stream.of(CardType.values()).
flatMap(type -> IntStream.rangeClosed(1, 4).mapToObj(num -> new Card(type, "CardName" + num))).
collect(toList());
для создания и добавления стандартных списков. Например (и обновлено для 4-х карт):
List<Card> deck = new ArrayList<Card>();
for (int i = 0; i < 4; i++){
deck.add(card1);
deck.add(card2);
deck.add(card3);
}
Если вы хотите свести к минимуму количество строк кода, есть способы инициализировать новый список с контентом. Попробуйте этот пост. Инициализация ArrayList в одной строке.
Во всяком случае, всегда пытайтесь закодировать самое простое решение, даже больше, начиная с нового языка.
add
вArrayList
.