I have been working on this code for hours how can I throw a NoSuchElement exception so that it stops the loop when it reaches the beginning of the list right now here is what the test case outputs with my code
expected: but was: Expected :a Actual :z
* Returns the data from next element in the set.
* @return the data from next element in the set
*/
public E next() {
// TODO : Implement
//returns the next element in the collection and advances
// the iterator by one location (updating both internal references).
// If one were to call next(), then prev(), then next(), the results of the two next() calls should be identical.
E temp = this.nextElem.info;
if (this.nextElem != null) {
//throw new NoSuchElementException("No element found");
return temp;
}
if (temp != nextElem.info) {
//E temp2 = this.nextElem.info;
//nextElem = nextElem.next;
//return temp2;
throw new NoSuchElementException();
} else {
return temp;
}
CodePudding user response:
What about just doing the following?
public E next() {
E temp = this.nextElem;
if (temp != null) {
return temp.info;
} else {
throw new NoSuchElementException();
}
}
Edit: Sorry, I forgot to explain what went wrong in your code.
What exactly will be
null
when you reach the end of the loop? Willthis.nextElem
benull
? Because if so, you will already get aNullPointerException
in the lineE temp = this.nextElem.info;
. Or, willthis.nextElem.info
benull
?Carefully read through your code. At first, you are assigning
this.nextElem.info
to the variabletemp
. Later, you are comparingtemp
tonextElem.info
in theif
-statement. Keep in mind thatthis.nextElem.info
andnextElem.info
are usually synonymous. Hence, what you are effectively doing is the following:if (nextElem.info != nextElem.info) {. As you can see, the condition will always evaluate to
falseand you will always go into the
elsebranch and never reach your
throw`.
CodePudding user response:
Consider that one of only two things can occur when the method is called:
- throw an exception because there is no next element
- return the next element and advance the cursor
So your algorithm could be summarized as:
public E next() {
// throw an exception because there is no next element
if there is no next element
throw exception
endif
// return the next element and advance the cursor
let info be the info at the next element
advance the cursor to next element
return info
}
How this is actually implemented depends on implementation details you have not provided. This appears to be a class assignment so pseudo-code should be sufficient to get you going. Note that the order of operations matters. For instance, if there is no next element then you shouldn't be trying to capture the value at the next element.