Supersaingamer88
Supersaingamer88

Reputation: 15

Remove element from object array (Java)

I am working on a card based game and I was working on an array editor tool (i.e.. delete a card object from the array, insert a card object, find a card, sort the cards, etc) and so I was work on the delete function and Im not sure how to accomplish this, I have an arrayTool interface set up with all the methods, an arrayToolModule class set up for implanting the methods and in my mainGame class I have a console method that prints out a simple console and wait for an input and then set all the necessary variables. Your help is greatly appreciated.

mainGame class:

        if(conIn==1)//Delete
        {
            System.err.println("Enter an Index: ");
            setIndex = in.nextInt();    
            AT.deleteCard(Deck, setIndex);
        }

arrayToolModule:

public Card[] deleteCard(Card[] CA, int index) {
        System.err.println("Delet was Called");

        
        CA = new Card[CA.length-1]
        
        for(int i=0;i<CA.length;i++)
        {
            if(i==index)
            {
                CA[i] = null;
            }
        
        for(Card i: CA)
        {
            System.out.print(" "+i.cardVal);
        }
        

        return CA;
    } 

This was my attempt I am not sure how to accomplish this.

Upvotes: 0

Views: 342

Answers (1)

Suic
Suic

Reputation: 443

You could use streams, which would make this really easy

public Card[] deleteCard(Card[] cards, int index) {
    Card cardToRemove = cards[index];
    return Arrays.stream(cards).filter(card -> !card.equals(cardToRemove)).toArray(Card[]::new);
}

or

public Card[] deleteCard(Card[] cards, int index) {
    return IntStream.range(0, cards.length)
            .filter(i -> i != index)
            .mapToObj(i -> cards[i])
            .toArray(Card[]::new);
}

or if you don't want to use streams

public Card[] deleteCard(Card[] cards, int index) {
    Card[] newCards = new Card[cards.length - 1];
    for (int i = 0, j = 0; i < cards.length; i++) {
        if (i != index) {
            newCards[j++] = cards[i];
        }
    }
    return newCards;
}

Upvotes: 1

Related Questions