Reputation: 37
all the questions i see are about using the return value, while i want to ask about not using it. i have a method that gets a book title, and remove all books with the same title from an array of books (library).
i wrote another method that gets a book title and remove the first book with the same title given, from the array (not 100% finished because the question is about it):
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;
}
i have another private method whose purpose is to close the gaps created in the array, and return the amount of books removed:
//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;
}
when i want to use the closeGap method, i get the value 1 returned, but i cant find a way to use it to break out of the for loop without forcing it badly. do i must use the returned value? is there a way to break out of the loop using it?
Upvotes: 0
Views: 63
Reputation: 144
you would do something as follows. Its a little vague on what set of values you want to remove. if you want to leave the loop if that returns 0 just replace
closeGap();
with
if(closeGap()==0)
break;
Upvotes: 0
Reputation: 12751
You can use break
to exit a for loop. E.g.
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;
}
Upvotes: 1