gpt4 book ai didi

java - 我必须使用方法的返回值吗?

转载 作者:行者123 更新时间:2023-12-02 11:19:34 25 4
gpt4 key购买 nike

我看到的所有问题都是关于使用返回值,而我想问的是不使用它。我有一个方法可以获取书名,并从书籍数组(图书馆)中删除具有相同标题的所有书籍。

我编写了另一个方法,它获取书名并从数组中删除给定的第一本书(没有 100% 完成,因为问题是关于它的):

public Book remove(String name)
{
Book bookRemoved= null;
for (int i=0; i<_noOfBooks; i++)
{
if (name.equals(_lib[i].getTitle()))
{
bookRemoved= new Book (_lib[i]);
_lib[i]=null;
closeGap();
}
}
return bookRemoved;
}

我有另一个私有(private)方法,其目的是缩小数组中创建的间隙,并返回删除的书籍数量:

//counts the amount of books removed and closes the gaps casued by removing them
private int closeGap()
{
int count=0;
//number of nulls
for (int i=0; i<_noOfBooks;i++) //run throughout array to find # of
nulls
{
if (_lib[i]==null);
count++;
}

//closing gaps
for(int i=0; i<_noOfBooks-1;i++)
{
int nextCell=i+1;
while (_lib[nextCell]== null) //find the next cell after _lib[i]
that isn't null
nextCell++;
if (_lib[i]== null)
{
_lib[i]= _lib[nextCell]; //fill nulled cell with nextCell-
temporarily alliasing
_lib[nextCell]=null; //remove nectCell value -remove
alliasing
}
}
return count;
}

当我想使用 closeGap 方法时,我得到返回值 1,但我找不到一种方法来使用它来打破 for 循环而不严重强制它。我必须使用返回值吗?有没有办法使用它来打破循环?

最佳答案

您可以使用 break 退出 for 循环。例如

public Book remove(String name)
{
Book bookRemoved= null;
for (int i=0; i<_noOfBooks; i++)
{
if (name.equals(_lib[i].getTitle()))
{
bookRemoved= new Book (_lib[i]);
_lib[i]=null;
if (closeGap() == 1) {
break;
}
}
}
return bookRemoved;
}

关于java - 我必须使用方法的返回值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50029611/

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