Break Loop After First Iteration - java

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;
}

Related

Check if String is within the range or not

I have a variable of type String loanTerm and want to check whether it is within the range 1-999. It can contain NA or number from 1-999 (exclude decimal) and can't be blank. I have used #NotNull, #Range(min=1,max=999) but couldn't able to perform complete validation.
in pojo class use the following set method for loanTerm.
setloanTerm(String str){
if(str != null && str !=""&&Integer.parseInt(str) >=0 && Integer.parseInt(str)<=999){
loanTerm=str;
}
}
If you want to see if string within a range the simplest way is to use if statement with String.compareTo() method:
if(str.compareTo(lower) > 0 && upper.compareTo(str) < 0){
System.out.println("inside the range");
}
First, check it whether it is empty or not. Than you can use Integer class to check whether it can be cast to Integer or not.
Integer validateLoanTerm(String loanTerm) {
if(!StringUtils.isEmpty(loanTerm) && Integer.parseInt(loanTerm) > 0 && Integer.parseInt(loanTerm) < 999) {
return Integer.parseInt(loanTerm);
}
return null;
}
I used Integer value as return value of the method. However if you do not need the value of it, you can just return a boolean from the method.

Linked list doesn't contain values greater than a certain number

How can I create a method that would check whether or not a linked list contains any number larger than a parameter?
Let's say we have the linked list
[ 8 7 1 3 ]. This would return true and
[ 10 12 3 2] would return false.
Would this work?
public boolean f(int k) {
for (int=0; int<linkedList.size(); i++) {
if (linkedList.get(i)>k)
return false;
}
else
return true;
}
Also, I need to mention, this method would not change the list in any way and it should still work if the list contains null elements.
Thanks!
With Java 8
public boolean f(int k) {
return !linkedList.stream().anyMatch(i-> i> k );
}
clarification: I assume that you want to return false from the method in the case that even a single element is higher then the given k. Hence I use anyMatch since we only need to look for one element that is higher. There is no need to loop over the whole list.
No this will not work how you have it currently. You need to loop through the whole list before returning. The only time you should return prematurely is if you find a reason to return false in this context. So move your return true outside of your loop and then you'd be fine.
Also, try to give meaning to your method and class definitions. Saying obj.f(12) doesn't really say much, whereas obj.noElementGreaterThan(12) says a lot more.
for example:
public boolean noElementGreaterThan( int k ) {
for( int i = 0; i < linkedList.size(); i++ )
{
if( linkedList.get(i) > k )
return false;
}
return true;
}
The reason this works is because it will loop through the entire list of objects, comparing each to the value passed in (k). If the value is greater than k, then it will return false, meaning in this case that it does have an element greater than k.
using streams you could do like this:
public boolean f(int k) {
List<Integer> filtered = linkedList.stream().filter(i -> i > k).collect(Collectors.toList());
return !filtered.isEmpty();
}

Missing a return statement somewhere?

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;
}

What to return when the requested index is out of bounds

If I have a method like this:
public Object getObject(int i) {
if (i >= 0 && i < objectList.size()) {
return objectList.get(i);
} else {
return
}
}
Is this the best way to deal with array index out of bounds errors, and what should I return in the else statement, null?
There is no absolute answer for this question, it depends on many things. However, if null is not a legal value, I would return null, if it's legal value I would throw an exception.
/**
* ...
* #return The element at index i, null if out of bounds.
*/
public Object getObject(int i) {
if (i >= 0 && i < objectList.size()) {
return objectList.get(i);
}
return null;
}
Or if null is a legal value:
public Object getObject(int i) throw IndexOutOfBoundsException {
if (i >= 0 && i < objectList.size()) {
return objectList.get(i);
}
throw new IndexOutOfBoundsException();
}
There is no such thing as "the best way", everything depends on your particular application. If "null" is somewhat recognizable (there are no nulls in your container) it can be an option. In some cases returning 0 may be the good option (when dealing with strictly positive number containers) and in others you could return element at i % size (so your container is cyclic). In general - it is always risky to return anything when asked for non existing element.
The most "frequent" approach is to raise an exception instead of returning anything.
You could implement the Null Object pattern.
Or you could implement a clamp, i.e. if the index is negative then return element at index 0 or if it is greater than or equal to size then return element at index size-1
But in your particular case the best thing to do is to raise an exception. This is what List#get does per default, so just leave it like that.
The reason is that you are explicitly asking for the value of an element at a certain index, i.e you expect that it is available. If not then there must be something wrong with the logic you use to determine that index.
I would throw an exception when the method is called with an illegal index. It does not make much sense to return anything for illegal calls.
Code would look like this:
public Object getObject(int i) {
return objectList.get(i);
}
Furthermore returning null pollutes other code with boilerplate null-checks.
Finally you're in good neighborhood with Java's List specification of List.get(int) when raising IndexOutOfBoundsException in such cases.
Its true there is no such thing like "best way" but you can handle exceptions by thinking what can cause them not to go to that point atleast.
public Object getObject(int i)
{
if(objectList == null || ojbectList.size()<=i)
return null;
if (i >= 0 && i < objectList.size())
{
return objectList.get(i);
}
}

Logical mistake or not?

I have written this function which will set
val=max or min (if val comes null)
or val=val (val comes as an Integer or "max" or "min")
while calling i am probably sending checkValue(val,"min") or checkValue(val,"max")
public String checkValue(String val,String valType)
{
System.out.println("outside if val="+val);
if(!val.equals("min") && !val.equals("max"))
{
System.out.println("Inside if val="+val);
try{
System.out.println("*Inside try val="+val);
Integer.parseInt(val);
}
catch(NumberFormatException nFE)
{
System.out.println("***In catch val="+val);
val=valType;
}
return val;
}
else
{
return val;
}
}
But the problem is if val comes null then
outside if******val=null
is shown.
Can any1 tell me is this a logical mistake?
And why will I correct?
If val is null, then the expression val.equals("min") will throw an exception.
You could correct this by using:
if (!"min".equals(val) && !"max".equals(val))
to let it go inside the if block... but I would personally handle it at the start of the method:
if (val == null) {
// Do whatever you want
}
Btw, for the sake of readability you might want to consider allowing a little more whitespace in your code... at the moment it's very dense, which makes it harder to read.
...the problem is if val comes null then outside if****val=null is shown. Can any1 tell me is this a logical mistake?
The output is correct; whether you want it to come out that way is up to you.
Your next line
if(!val.equals("min") && !val.equals("max")){
...will throw a NullPointerException because you're trying to dereference val, which is null. You'll want to add an explicit check for whether val is null:
if (val == null) {
// Do what you want to do when val == null
}
you should use valType instead of val to check either minimum or maximum is necessary to check.
My advice to you in such cases to use boolean value or enum instead of strings. Consider something like that:
/**
* check the value for minimum if min is true and for maximum otherwise
*/
public String checkValue(String val, boolean min){
if (min) {
// ...
} else {
// ...
}
}
If you need to compare strings against constants you should write it the other way around to make it null-safe:
if (! "min".equals(val))
And while this is mostly a style issue, I would make all method arguments final and not re-assign them (because that is confusing), and you can also return from within the method, not just at the end. Or if you want to return at the end, do it at the very end, not have the same return statement in both the if and the else branch.

Categories

Resources