putting check to check some predetermined values and excute the buisness logic - java

I have an object ar which contains mainy method so one of the method is getrookic() like as shown below..
ar.getrookic()
now its return type is String
now it return values like 23, 34 like these....
now i have to put an condition where in advance i know that i have to do some logic
when this methods will return the value 66,77,64
so what shall i put in if check...
if (!ar.getrookic().equals(66) ||!ar.getrookic().equals(77) || !ar.getrookic().equals(64))
{
//do some logic
}
please advise it is correct approach..!

First, you should not be performing not on your String equality testing. If ar.getrookic() returns a String then you need to test String equality. If your function actually performs work then you should save the first reference -
String str = ar.getrookic();
if (str.equals("66") || str.equals("77") || str.equals("64"))
{
//do some logic
}

Related

How do I call two functions inside an if statement that is inside a for loop in Java?

I am supposed to implement two functions that I already created (named isTargetWithinRange (what it does: given a target, this says whether a target is within range) and isTargetVisited (which checks that the target wasn't already captured)).
In this part, I am supposed to get the index of an unvisited target within the "range" (maximum distance to my target) of my current location. To do this, I am trying to create a for loop that contains an if-statement that calls my two variables.
The trouble that I am having is that I do not know how to call functions within the if-statement (that is within a for loop). I am trying to say within the if-statement that if isTargetWithinRange returns true or if isTargetVisited returns false, then the result is -1 (which in this case represents a target that is not yet captured).
if (isTargetWithinRange(i) return true || isTargetVisited(i) return false)
return -1;
}
}
I know that this question is probably incredibly confusing...but I really need help. I will try and clarify/define anything I can to get some help...
Something like this should do the job
if (isTargetWithinRange(i) || !isTargetVisited(i)) {
return -1;
}
You need to separate the method that returns true or false ( a predicate) from the action you want to take depending on the result. For example:
if(doIReturnTrue()) { // if true do something } .
The if statement will receive the result from the function, so you don't need
isTargetWithinRange(i) return true
Instead just pass the result of the method return into the if statement
if(isTargetWithinRange(i)){ // do if true etc }
To test a false result negate the return value using the logical not ! operator
if(!isTargetVisited(i)){ // do if true }
In the above when isTargetVisited returns false apply the 'logical not' to change this to true
I see that you might be new in Java. A function will return a value, in your case it is probably a boolean. Therefore you can use the following to achieve your result:
if (isTargetWithinRange(i) == true || isTargetVisited(i) == false) {
return -1;
}
Since the function will return a value, the == will check if the returned value is equal to what you want it to be.

What keywords should I use in a for-loop when using if-statements?

Let's assume that we have a for-loop that will loop through a collection or array of Strings. In that case, I am searching for a specific keyword (ex. hey) here's how I usually achieve that:
for (String result : strings)
{
if (result == "hey")
{
// Do something with that.
break;
}
}
Now, the question arises from that code snippet is, should I place a keyword (return or break) when the if-statement returns true so the loop will not continue? If not, what will happen and what's the correct way of going about it.
Edit: What happens when you use break and return? What's the difference?
Let's put your code inside a method:
private void foo()
{
for (String result : strings)
{
if (result.equals("hey"))
{
// Do something with that.
break;
}
}
bar();
}
If you use break;, the loop will terminate and bar will be reached. If you use return, the method will terminate and bar won't be executed.
Note that comparing strings should be done using equals, == compares references and not content.
If you know the word can only be found once you can surely place an break; statement so the loop won't continue after finding the match.
If you can have more than one match and you want the if block to be executed for each of those matches you should NOT put the break statement since it will stop the execution of the loop after the first match is found.

Methods vs Method assigned to variables in Java

I'm sort of confused, I guess this question is just a matter of preference, I just want to understand the difference of the following code.
if (IsRegistered() == true) ...
public boolean IsRegistered()
{
private boolean status = false;
// blah blah code here
return status;
}
vs
isRegistered = IsRegistered();
if (isRegistered)
I know both would work, I'm not being pedantic but I just want to understand so I would know my way around.
if (isRegistered() == true) ...
This is verbose since you know if it returns true it will do it, if not, it wont. So its the same as doing:
if (isRegistered()) ...
What it does, its just getting the returning boolean value from the method and checking the condition in the if statement.
Now if you wanted to check the boolean value again, you would need to re-call the method (which may have to do something complex to return that value), BUT if you assign it to a variable first and then check the condition, like this:
boolean isRegistered = isRegistered();
if (isRegistered)...
Later on the code you can just do it again without calling that method again.
if (isRegistered)... // n lines later.
hence, avoiding executing the process again.
At the end of the day, it pretty much depends on what you need to do.
When you invoke a method which has a non-void return type, the method itself resolves to a value the same way that using a variable does. You can either use that value directly or assign it to a variable and use that.
Just use:
if ( IsRegistered() )
It's the most readable code. Having a variable to "unbox" the method will not do any good; the compiler picks it up and replaces it into the control code itself in an internal optimization pass.
Also, the performance of your IsRegistered() method, when the self-optimization of machines is put aside, depends on how your "my code here" works:
source : {
private boolean status = false;
// blah blah code here
return status;
}
optimization-passed : {
return false; // When internal code does not modify "status"
preturn _status; // When internal code modifies "status"
}

How can I use more than one comparison with the .equals function or is there another function that I can use to check?

BTW, this is only a short version of my code, the only problem I have is from .equalsIgnoreCase over. I have tried the pipe operator || and that has not worked for "or" either. Let me know, thanks. Its in Java too.
if(sWord.substring(0,sWord.length()).equalsIgnoreCase("ch","sh","s","x","z"
{
lblPluralOutput.setText(sWord + "es");
}
}
No, you cannot do it directly like that. Put all possible values in an array and check your string is in that array or not.
String[] items ={"ch","sh","s","x","z"};
for (String item : items) {
if (sWord.substring(0,sWord.length()).equalsIgnoreCase(item)) {
lblPluralOutput.setText(sWord + "es");
break;
}
}
More over sWord.substring(0,sWord.length()) again gives you same string back. Is it a typo ?
Those functions only take one parameter.
If you want to check whether a string is equal to either of two things, you need to check separately:
if (a.equals(b) || a.equals(c))
You can't use String#equalsIgnoreCase(Str) cause only receives one parameter. But you can
make your util method.
Something like this. We can make it generic.
public final class UtilClass{
private UtilClass(){}
public static <T> boolean isSomeOneEquals(T myParam, T ... a){
return Arrays.asList(a).contains(myParam);
}
}
So in your example just put:
UtilClass.isSomeOneEquals( sWord.substring(someIndex,sWord.length()).toLowerCase(), "ch","sh","s","x","z" );

Searching through a collection of an array list pair [duplicate]

This question already has answers here:
How to compare two java objects [duplicate]
(5 answers)
Closed 9 years ago.
I am trying to search through a collection of an ArrayList if pairs. What I want to be able to do, is to go through the collection and find the first value in a pair and return the second value of that pair. The problem I am having is that the check I have to find the first value doesn't seem to be working, so every time I search, I end up returning null. I know that the problem exists with my if statement, but I cannot seem to sort out what it is I am doing wrong. Since this is a homework assignment, I can't show all the code to my pair class, or my pair list class, but I can show you the method I have for searching the first value:
public S findFirst(F firstValue) {
Iterator<Pair> myIter = this.iterator();
S tmp2 = null;
while (myIter.hasNext()) {
Pair tmp1 = myIter.next();
if (tmp1.getFirst() == firstCall) {
tmp2 = (S) tmp1.getSecond();
}
}
return tmp2;
}
If I throw in an else statement that just calls what I am attempting to do in my if check, like this:
else{
tmp2 = (S) tmp1.getSecond();
}
then whenever I test for the first value, I get the second value, so I know I am at least on the correct path, but I am assuming that I am doing something wrong with what I am checking for in my if statement. Does anyone know how I can correctly do this, (and please bear in mind that this is homework, so a guide to how to figure this out is far more valuable to me than just some random answer, I want to learn, not just be given an answer) Thanks in advance!
Don't use == to compare objects. Override and use equals().
I think
if (tmp1.getFirst() == firstCall)
should probably say
if (tmp1.getFirst().equals(firstValue))
The important difference is that == checks whether two expressions refer to the exact same object. You're more interested in knowing whether your two expressions actually refer to objects that are equal.
Try this:
if (tmp1.getFirst().equals(firstValue))
instead of
if (tmp1.getFirst() == firstCall)
Also you can override your own equals method.
You should never use == to compare objects.
Check How to compare two java objects
What Matt says, (don't use == ) but I think a bigger problem is that you don't return the 'first' encounter.... your if statement should look like:
public S findFirst(F firstValue) {
Iterator<Pair> myIter = this.iterator();
while (myIter.hasNext()) {
Pair tmp1 = myIter.next();
if (firstValue.equals(tmp1.getFirst())) {
return (S) tmp1.getSecond();
}
}
return null;
}

Categories