Reputation: 229
EDIT: Solved. Returning a 0 works, apparently!
Ok so long story short, I have to return an int value, but nothing when a Linked List is empty. How do I do it?
public int countDuplicates() {
int duplicates = 0;
ListNode current = front;
int num = current.data;
current = current.next;
while(current != null) {
if(current.data == num) {
duplicates++;
} else {
num = current.data;
}
current = current.next;
}
return duplicates;
}
When I try this:
if(front == null) {
return ;
}
This doesn't work. What can I do?
Upvotes: 3
Views: 9643
Reputation: 1
public boolean isEmpty(){
if (head == null) return true;
else return false ;
}
Upvotes: -1
Reputation: 15729
If you don't want to (or can't) throw an exception, return some "exceptional value", such as a negative number. For example, Java has a lot of indexOf(Object somethingToLookFor)
methods that return a -1 if the item isn't found.
In your example, -1 works as exceptional because there can never be -1 duplicates.
Personally, I would just return 0 for an empty List. An empty list has 0 duplicates. But if the spec insists on something exceptional, return -1.
Upvotes: 0
Reputation: 6592
To keep the code as you have it now, you must either return an int, throw an exception, or exit.
Return an int: You'll have to specify a certain int value as the "fail" value and make sure that it is never the case that this value is hit during "normal" execution.
Throw an exception: Detailed in another answer - you've already shot it down.
Exit the program... if it makes sense to do that.
The best option may be to change the code - make the function return an Integer, for example, so the null
option is there. There are surely other ways to work around it, as well.
Upvotes: 1
Reputation: 270
You could return a negative value or change the return type to string and parse the result to int.
Upvotes: 0
Reputation: 5638
you can change the return value from int to object like this
public Object countDuplicates() {
if(////condition)
return ///int;
else
return null;
Upvotes: 0
Reputation: 8160
If your method returns an int
you must determine an acceptable value to represent "nothing". Such as 0
or if valid results are >= 0
, use a negative value such as -1
to indicate "nothing".
Alternatively, modify your method to return an Integer
object in which case you can return null
.
Upvotes: 3
Reputation: 8215
It is possible for you to either define a fixed value, such as Integer.MIN_VALUE
, that would indicate that the list is empty, or change the declaration of your method to public Integer countDuplicates()
, and return null
when the list is empty.
Upvotes: 2
Reputation: 213351
You can rather throw an IllegalArgumentException
: -
if(front == null) {
throw new IllegalArgumentException("List is empty");
}
Upvotes: 5