Missing a return statement somewhere? - java

I'm working on a basic Java assignment for school. This snippet involves searching for a specific part number in an ArrayList. When I try to compile, the IDE says I have a missing return statement. However, I can't see where it is. Do I need a return statement following the increment of the index? If so, then the return null becomes unreachable. Thank you guys very much.
public InventoryItem findInventoryItem(int searchPartNumber)
{
int index = 0;
boolean searching = true;
while (index < items.size() && searching){
InventoryItem inventoryItem = items.get(index);
int fetchedPartNumber = inventoryItem.getPartNumber();
if(fetchedPartNumber == (searchPartNumber)){
searching = false;
return inventoryItem;
}
else{
index++;
}
if(searching){
return null;
}
}
}

your code has several problems:
after you compared first item in list and it does not match - you will stop comparing, as searching is true and you will return null
in case of empty list you need to return null too
here is the fixed version:
public InventoryItem findInventoryItem(int searchPartNumber) {
for (InventoryItem inventoryItem : items)
if (inventoryItem.getPartNumber() == searchPartNumber)
return inventoryItem;
return null;
}

The method expected a return value in all cases. This means you have to add a return value in the else-block, too. Or you could add a return value only once at the end of all statements.

you're not handling the case where search will not be true.
That is,
if(searching){
return null;
}
Where is the else part handled here?

No matter what happens in your method, there has to be some value returned (even if it is null).
Right now, if you never get into your while (because that condition isn't fulfilled to begin with -> like when items.size() is 0), your method won't return anything.
In other words: Put a return null; after the closing bracket of your while loop.
Another important note: You do realize that this while will always only look at the first item, right? Because if your first item is not the one you're searching for, your variable searching will still be true, which will then force the method to return null (without looking at any other items)

You are missing a return statement right at the end, after the while loop.
This is needed to handle the case where the while loop guard becomes false, either by items being empty, or searching being set to false.
The compiler has no way of determining whether these will never become false, so you it requires you to return in case they do.

All functions that have a type (aren't void) require that you return something based on the method signature. This means that you must return something in ALL cases. You haven't included the case where searching is not true, and must return something if that is the case.
if(searching){
return null;
} else{
//return something else
}
It is important to note though that in this case the else is implicit, and therefore you don't actually have to provide the else. You could instead just do this:
if(searching){
return null;
}
//return something else
Keep in mind that if searching is true, it will return null and "return something else" will never be called.

Do like this
public InventoryItem findInventoryItem(int searchPartNumber)
{
int index = 0;
//boolean searching = true; comment out this line
InventoryItem inventoryItem = null; //declare null InventoryItem here
while (index < items.size())
{
inventoryItem = items.get(index);
int fetchedPartNumber = inventoryItem.getPartNumber();
if (fetchedPartNumber == (searchPartNumber))
{
//searching = false; comment out this line
break; //do something to get out from while loop
}
else {
inventoryItem = null;
index++;
}
}
return inventoryItem; //if found then it will have item otherwise null
}

First you need to return if items.size equals zero. Second you need to return if you find nothing. Third I can't see any usefulness of the variable searching.
You could change your searching function a bit. The final form would be something like this:
public InventoryItem findInventoryItem(int searchPartNumber) {
int index = 0;
while (index < items.size()){
InventoryItem inventoryItem = items.get(index);
int fetchedPartNumber = inventoryItem.getPartNumber();
if(fetchedPartNumber == searchPartNumber)
return inventoryItem;
else
index++;
}
return null;
}

Related

What is the correct syntax of a method that deletes part of a list and returns true if succesful?

I m trying to create a method that searches the content of a list called authors looking for the element (the author's name) given as arg, and then deletes the specific field. If successful it returns true. But it won't work for some reason. I believe the error lies in the authors.remove(authorName); because the main class will not erase anything when given the order Book.removeAuthorByName("White");.
public boolean removeAuthorByName(String authorName){
boolean val = authors.contains(authorName);
for (int i = 0; i <= numAuthors; i++){
if(val = true){
authors.remove(authorName);
authors.trimToSize();
}
}
return val;
}
public int listSize(){
return authors.size();
}
Little more concise and better will be
public boolean removeAuthorByName(String authorName){
int index = authors.indexOf(authorName);
if(index > -1){
authors.remove(index);
return true;
}
return false;
}
First of all, you should check whether your list supports the remove(Object) method; it does because otherwise you would have received an UnsupportedOperationException.
You can simply have to call authors.remove(name); the method will return true if the passed name was found and deleted successfully - see the documentation.
Remove the while loop check using if clause. Also check case sensitivity
if(list.contains(authorname)){
list.remove(authorname);
return true;
}
else
{
return false;
}

Break Loop After First Iteration

I have a List that contains many rows of data.What i want to do is return only the first iterated value and nothing else.
public int getnumber() {
for (Bike temp : bikes) {
return temp.getBikeID();
break;
}
}
I tried something like the above..but the break statement is unreachable. How may i achieve this ?
I know that i could still just declare a variable outside of the loop then assign the value in the loop but the returned value will be the last row.
This is because of the return statement before break. The return statement will take the execution to the calling method. so, the break statement is unreachable.
You don't need to iterate to get the first value of the collection. The first index would be 0. so, just make it
if(bikes!=null && bikes.size() > 0)
return bikes.get(0).getBikeId();
return -1; // `-1` denotes failure or put anything relevant to failure
Do not loop and try directly :
return bikes.get(0).getBikeId();
Try like this -
// null and size check to make sure if there is something on 0 index
return bikes != null && bikes.size > 0 ? bikes.get(0).getBikeId() : 0;
Simply delete the break statement. In fact, this is all you need:
for (Bike temp : bikes) return temp.getBikeID();
return -1;
In place of return -1 put the behavior you prefer for the "not found" case.
You can access you list's indices via .get() directly. No need for an iteration if you only need one or a hand full of specific elements:
public int getnumber() {
int result = 0;
if (bikes != null && bikes.size() > 0)
result = bikes.get(0).getBikeID();
return result;
}
Or even shorter, with the use of the ternary operator (condition ? true : false;):
public int getnumber() {
return (bikes != null && bikes.size() > 0) ? bikes.get(0).getBikeId() : 0;
}

Why do I receive the error "This method must return a result of type ..."?

Can anyone see why I would receive the error "This method must return a result of type Card", when I clearly returns that variable "card" which is of type Card?
public Card playCard(int id){
int i = 0;
for (Card element : hand){
if (i <= hand.size())
{
if (element.getID() == id)
{
Card card = hand.get(i);
hand.remove(i);
return card;
}
else
{
i++;
}
}
else
{
throw new NullPointerException("Card does not exist in hand");
}
}
}
Your method doesn't return anything except in one possible scenario. It has to return something (or throw an exception) in all possible scenarios.
I think you meant to do this:
public Card playCard(int id){
for (Card element : hand) {
if (element.getID() == id) {
return element;
}
}
throw new SomeAppropriateException("Card does not exist in hand");
}
...but I'm guessing a bit (as I don't know what hand is, but it looked a lot like a List). That code will always either execute the return statement or throw an exception, there's no way to get to the end of the method without one of those things happening.
Note that throwing a NullPointerException for a condition that isn't caused by a null pointer is a Bad Idea(tm). (It's also best to be consistent in where you put your { and }.)
As hinted at by Tarlen, your code would need to be modified as such:
public Card playCard(int id){
int i = 0;
for (Card element : hand){
if (i <= hand.size())
{
if (element.getID() == id)
{
Card card = hand.get(i);
hand.remove(i);
return card;
}
else
{
i++;
}
}
else
{
throw new NullPointerException("Card does not exist in hand");
}
}
return null;
}
I believe that will account for all of the possible routes your program will need to take. You always gotta keep track of returning something EVERYWHERE the method can exit. If it can exit without hitting a return statement, you'll see that error.
Your method signature is:
public Card playCard(int id){
which means you must return a Card object. Your code only has one return statement, but there are many paths through the code. You must return a Card object for each path
It is because if hand is empty, then no value is being returned.
Add a return or a throw after your for loop.
You need to have a default return statement (or exception/error) for the whole method or at least one return statement (or exception/error) for every possible execution path in your code. As it is right now you have neither of them.

public boolean removeStudent(int id)

Help me fix error please.
public boolean removeStudent(int id)
{
for (Student student : this)
{
if ((student.getID()) == (id))
return true;
id.remove();
}
return false;
}
Error: int cannot be dereferenced.
I'm trying to remove a student from a list based on id. But the .remove is incompatible with ints.
id is an int, a primitive type, so it doesn't have any methods.
id.remove(); //will never compile
Change your code to
for (int x =0; x < this.size();x++) {
//your if should contain the removal and the return statements
if ((this.get(x).getID()) == (id)) {
this.remove(this.get(x));
return true;
}
}
return false;
Don't you mean to call student.remove() or something along those lines?
Also, that code won't be hit with the return true line before it.
This code does not look very well. First off: The remove call is wrong and remove is always called as your if statement is not encapsulated with brackets.
Reindent your code and you will see the problem:
public boolean removeStudent(int id)
{
for (Student student : this)
{
if ((student.getID()) == (id)) {
return true;
}
id.remove();
}
return false;
}
See what you are currently doing: once you hit a student with matching ID, you will immediately jump out of the method, returning true. Until then, you are removing all student you iterate. i.e. You are removing all students, until you found a matching one.
It don't look quite normal to me.
I bet what you want to do is: remove all students with matching ID. If any student is removed, return true, else return false.
If so, try to understand this piece of code:
(I am not giving you direct answer. If you can understand what's going on in this piece of code then you can fix yours easily)
// print out only odd numbers in the list, and return true if there is any.
boolean printOdd(List<Integer> numbers) {
boolean oddFound = false;
for (int i : numbers) {
if ((i % 2) != 0) {
System.out.println("Odd Number Found: " + i);
oddFound = true;
}
}
return oddFound;
}
More problem in your code:
You don't seems using for-each look correctly. Is your class a Collection?
for (Type a : b) {...}
expect b to be a Collection (more precisely, Iterable) or an array.
Another problem is, id is an integer, what do you expect an id.remove() will do? You are telling an Integer to do "remove()"
I assume you are doing something like this.studentList.remove(id) or this.studentList.remove(student) ?

Ways to check if an ArrayList contains only null values

I was looking through the code for an old Android application of mine, and I saw one thing I did to the effect of this:
boolean emptyArray = true;
for (int i = 0; i < array.size(); i++)
{
if (array.get(i) != null)
{
emptyArray = false;
break;
}
}
if (emptyArray == true)
{
return true;
}
return false;
There has to be a more efficient way of doing this -- but what is it?
emptyArray is defined as an ArrayList of Integers, which are inserted with a random number of null values (And later in the code, actual integer values).
Thanks!
Well, you could use a lot less code for starters:
public boolean isAllNulls(Iterable<?> array) {
for (Object element : array)
if (element != null) return false;
return true;
}
With this code, you can pass in a much wider variety of collections too.
Java 8 update:
public static boolean isAllNulls(Iterable<?> array) {
return StreamSupport.stream(array.spliterator(), true).allMatch(o -> o == null);
}
There is no more efficient way.
The only thing is you can do, is write it in more elegant way:
List<Something> l;
boolean nonNullElemExist= false;
for (Something s: l) {
if (s != null) {
nonNullElemExist = true;
break;
}
}
// use of nonNullElemExist;
Actually, it is possible that this is more efficient, since it uses Iterator and the Hotspot compiler has more info to optimize instead using size() and get().
It's not detection of contains only null values but it maybe be enough to use just contains(null) method on your list.
Simply Check it worked for me. Hope will work fine for you too!
if (arrayListSubQues!=null){
return true;}
else {
return false }
I use to do something like this :
// Simple loop to remove all 'null' from the list or a copy of the list
while array.remove(null) {
array.remove(null);
}
if (CollectionUtils.isEmpty(array)) {
// the list contained only nulls
}

Categories

Resources