我需要创建一个方法,将卡添加到Flashcard框中,这是我创建的二维数组。它有三个String参数(单词,定义,主题)。 该方法将采用三个String参数 - 新Flashcard的信息。它会 返回一个布尔值,指示卡是否已成功添加到框中。 它将尝试以下列方式添加卡: 如果卡所用的主题在盒子中,并且卡片尚未在盒子中,那么我可以将卡片添加到盒子中。如果我想要添加卡,并且行中没有足够的空间与主题相对应,那么我需要增加数组,以便每个主题都有空间 还有一张卡。如果卡所用的主题不在框中,那么我需要将卡存储在下一个空行中(这类似于将主题添加到框中)。如果没有空行,那么我需要增加数组并添加一行。如果卡已经在框中,那么我无法将其添加到行中。请帮助,我将其作为一种学习工具。
这是写出的伪代码,需要遵循:
public FlashcardBoxAddCardHelp
{
public boolean addCard(String subject, String word, String definition)
{
Flashcard toAdd = new Flashcard(subject, word, definition);
for(loop through rows)
{
for(loop through columns)
{
if(current card is the same as the card to add)
{
return false;
}
}
}
int subjectIndex = -1;
for(loop through rows)
{
if(currentRow has subject I want)
{
subjectIndex = currentRow;
}
}
if(subject is in the box) //
{
if(there is room in that row)
{
add the card to the first free slot in that row
}else // do this last!
{
// grow the array to add a column
// add the card to the new column for your subjIndex row
// update the counts to keep track of how many columns you have
// and how many columns you have room for
}
}else
{
if(there is room for a new subject)
{
add the card to the first free row
}else // do this last!
{
// grow the array to add a row
// add the card to the first slot in that new row
// update the counts to keep track of how many rows you have
// and how many rows you have room for
}
}
return true;
}
}
答案 0 :(得分:0)
确定。你不能真正在数组中添加一个插槽,你必须创建一个长度比以前的数组长1的数组,然后将旧数组设置为等于新数组,并将所有旧信息复制到数组中。新阵列。使用ArrayLists的ArrayList可能更容易。试试这个:
ArrayList<ArrayList<FlashCard>> subjects = new ArrayList<ArrayList<FlashCard>>();
然后当你想要添加一张闪卡时:
if (subject there) // Find subject using for loops
{
subject = /*that subject*/;
subject.add(flashcard);
}
else
{
ArrayList<FlashCard> subject = new ArrayList<FlashCard>();
subject.add(flashcard);
subjects.add(subject);
}
评论是否需要澄清。即其余的查找代码,但它非常简单。