gpt4 book ai didi

java - 对象数组 - 从数组中删除对象

转载 作者:行者123 更新时间:2023-12-02 07:49:54 26 4
gpt4 key购买 nike

我被分配了创建臭名昭著的“UNO”游戏的任务。我遇到了其中一种方法的麻烦,如果玩家选择玩它,该方法应该“删除”玩家手中的一张卡对象。我想你必须玩过UNO才能理解。不管怎样,这里是该方法应该是什么的描述:

Create a method named removeCardFromHand that takes an integer index as a parameter and both removes and returns the Card at that position of the player's hand. If the specified index does not correspond to one of the cards in the hand, the method should throw an IndexOutOfBoundsException. After the card has been removed, the remaining cards should be rearranged as needed so that they occupy the leftmost positions of the array. One way to do this is to move the rightmost card into the position of the card that is being removed. For example, if the hand is currently the four cards {blue 3, red 2, yellow 7, green 1} and you are removing the card at position 1 (the red 2), you could replace it with the last card (the green 1), and thus the resulting hand would be: {blue 3, green 1, yellow 7}.

不幸的是,我不允许使用数组列表或 vector ,只能使用简单的旧数组

这是迄今为止我的代码:

public Card removeCardFromHand(int n)
{
Card c = cards[n];
for(int i = n; i < cards.length; i--)
{
cards[n] = cards[n + 1];
}
c = cards[cards.length - 1];
return c;
}

显然这是不对的,但我只是不知道该怎么做。

最佳答案

你几乎明白了,除了你将数组中的所有卡片向左移动一个位置,因此你要删除最左边的卡片,并将“删除”的卡片留在数组中,除非它碰巧是最左边的一个。您只想从已删除的卡右侧(较高索引)的卡开始进行移动。因为我认为这是家庭作业,所以我会让您找出需要更改的一个表达式;-)

关于java - 对象数组 - 从数组中删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10340543/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com