Java NoSuchElementException error

  • Context: Comp Sci 
  • Thread starter Thread starter magnifik
  • Start date Start date
  • Tags Tags
    Error Java
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
9 replies · 4K views
magnifik
Messages
350
Reaction score
0
I am writing code for a doubly linked list, but when I try to compile it, I am getting an error when trying to throw the NoSuchElementException() function. Here is the part of the code concerning the issue:

// _size is an integer that keeps track of the number of elements. in this case, i am checking if the list is empty
public Object removeBack() {
if (_size == 0) {
throw new NoSuchElementException();
}
Node node = new Node();
Node cursor = _tail._prev;
cursor._next._prev = cursor._prev;
cursor._prev._next = cursor._next;
_size--;
}

i am wondering.. what's wrong with it? am i calling it incorrectly?
 
Physics news on Phys.org
magnifik said:
I am writing code for a doubly linked list, but when I try to compile it, I am getting an error when trying to throw the NoSuchElementException() function. Here is the part of the code concerning the issue:

// _size is an integer that keeps track of the number of elements. in this case, i am checking if the list is empty
public Object removeBack() {
if (_size == 0) {
throw new NoSuchElementException();
}
Node node = new Node();
Node cursor = _tail._prev;
cursor._next._prev = cursor._prev;
cursor._prev._next = cursor._next;
_size--;
}

i am wondering.. what's wrong with it? am i calling it incorrectly?

NoSuchElementException is used when an enumeration doesn't have a particular element. I think you want to use NoSuchFieldException.
 
i tried to change it to NoSuchFieldException, but I am still getting the same error.
 
Mark44 said:
What's the error that you're getting?

Cannot find symbol
 
i got it to work by removing the {} symbols.
 
magnifik said:
i got it to work by removing the {} symbols.
They're called braces. In any case, that doesn't make sense to me. Your removeBack method looked fine to me with them, so removing the braces on your if statement shouldn't have made any difference.
 
Mark44 said:
They're called braces. In any case, that doesn't make sense to me. Your removeBack method looked fine to me with them, so removing the braces on your if statement shouldn't have made any difference.

It doesn't make sense to me either, but I didn't change any of my code except for the removal of the brackets and it wasn't throwing an error.
 
magnifik said:
It doesn't make sense to me either, but I didn't change any of my code except for the removal of the brackets and it wasn't throwing an error.

So add the curly braces again and check if it throws an error again.
To be honest, I expect that it won't throw an error.