0

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.

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.