简体   繁体   中英

Java- Calling the integer part of an object array

I have an object array in which each object in the array has an integer component along with a string and a buffered image component. My code creates a deck of fifty two cards each with a unique integer. I want to make a program that finds cards based on there integer value.

So for example if the integer 10 corresponds to the king of spades, the user can enter in the number 10 and the program will find the king of spades and move it to the top of the deck. How can I find a card based on only its' integer value?

public class Card_Class {
    private String suit, face;
    private int value;
    public BufferedImage cardImage;

public Card_Class(String suit, String face, int value, BufferedImage card) {
    this.suit = suit;
    this.face = face;
    this.value = value;
    cardImage = card;

}

public static void main(String[] args) throws IOException {

    Card_Class HeartKing = new Card_Class("Hearts", "King", 13, ImageIO.read(new File("HeartKing.jpg")));
    }
}

Here is the deck constructor:

public class Deck {

public static Card_Class[] deckOfCards;
private int currentCard;

public Deck() throws IOException {

    String[] faces = {"Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"};
    String[] suits = {"Diamonds", "Clubs", "Hearts", "Spades"};
    deckOfCards = new Card_Class[52];
    currentCard = 0;

    final int width = 88;
    final int height = 133;
    final int rows =4;
    final int columns = 13;

    BufferedImage bigImage = ImageIO.read(new File("AllCards.png"));
    BufferedImage tempCardImage;

    for(int suit=0;suit <4; suit++){

        for(int face=0;face<13;face++){
            tempCardImage = bigImage.getSubimage(
                    face*width+(face*10)+8,
                    suit*height+(suit*10)+38,
                    width,
                    height);
            deckOfCards[(face+(suit*13))] = new Card_Class(suits[suit],faces[face],(13*suit+face),tempCardImage);
        }
    }     
   }

You can do something like this:

 private Card_Class find(int number){
    Predicate<Card_Class> p1 = c -> c.value == number;
    return Arrays.stream(deckOfCards).anyMatch(p1);
 }

Your predicate is the matching criteria, in this case being the value matching the given number.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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