【发布时间】:2018-04-25 19:02:08
【问题描述】:
我看到的所有问题都是关于使用返回值的,而我想问的是关于不使用它的问题。 我有一个获取书名的方法,并从一系列书籍(图书馆)中删除所有具有相同标题的书籍。
我编写了另一种方法,该方法获取书名并从数组中删除具有相同标题的第一本书(不是 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;
}
我有另一个私有方法,其目的是关闭在数组中创建的间隙,并返回删除的书籍数量:
//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 循环而不会严重强制它。 我必须使用返回值吗?有没有办法使用它来打破循环?
【问题讨论】:
-
如果你想提前终止一个for循环,你可以使用break。
-
调用者可以放心地忽略返回值。我认为我使用的最后一个不允许使用的语言是
Modula-2 -
不清楚您是在询问如何使用(或不使用)方法的返回值,还是在询问如何跳出循环。它们是不相关的概念。