Java: compare String var to int - java

I request variable from the server (String xxx) and receive it properly (it equals 1).
Then I want to use it in 'if' statement, so I do :
if(xxx.equals(String.valueOf(1)))
but it doesn't work the way it supposed to be - it should be equal, but it works as it is not.
I'm out of solutions. What am I doing wrong ?

See what happens after trime xxx
if(xxx.trim().equals(String.valueOf(1)))

Try this:
if(Integer.valueOf(xxx.trim()) == 1)
Rather compare them as integers than as strings.

try this:
if (xxx.trim().equalsIgnoreCase(intValue+"") {
}
or
if (xxx.trim().equalsIgnoreCase("1")) {
}

Related

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

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
}

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

Error while using ternary operator

I'm writing my Code with Eclipse Juno and I'm using a hash table to set my dataImportObject depending on the entries in it.
Could anyone please tell me whats wrong about this:
ht is my hashTable with <String, Integer> pairs in it
(ht.containsKey("DEVICE_ADDRESS")) ?
dataImportObject.setDevice_Address(dataitems[ht.get("DEVICE_ADDRESS")]) :
dataImportObject.setDevice_Address("");
Could anyone please tell me whats wrong about this
Two things:
The conditional operator can't be used as a statement on its own, only as an expression
I assume these set methods have void return types, so they can't appear as operands in the conditional operator
Three options:
Use an if statement:
if (ht.containsKey("DEVICE_ADDRESS")) {
dataImportObject.setDevice_Address(dataitems[ht.get("DEVICE_ADDRESS")]));
} else {
dataImportObject.setDevice_Address("");
}
Use the conditional operator inside the setDevice_Address call, or even clearer, beforehand:
String address = ht.containsKey("DEVICE_ADDRESS")
? dataitems[ht.get("DEVICE_ADDRESS")] : "";
dataImportObject.setDevice_Address(address);
If you know that your hashtable won't have any null values, you can avoid the double lookup:
Integer index = ht.get("DEVICE_ADDRESS");
String address = index == null ? "" : dataitems[index];
dataImportObject.setDevice_Address(address);
You can't set the return type of ternary condition to void.
Use if else for that.
Possible duplicate

Checking for either/or with an EnumSet

So I'm converting some bitfields in our application to use EnumSet instead, and I'm curious if there's a better way to do a comparison for X|Y. Currently we do something like:
if(bitfield & (X | Y) != 0) {
//do stuff
}
The EnumSet equivalent seems to be:
if(enumSet.contains(X) || enumSet.contains(Y)) {
//do stuff
}
Is there a cleaner way to do this? I know you can check for containsAll() like so:
EnumSet flagsToCheck = EnumSet.of(X, Y);
if(enumSet.containsAll(flagsToCheck)) {
//do stuff
}
But that's for a scenario where you want to know if (X & Y) is set. Is there an equivalent way to check for (X | Y)? I would think there would be something like a containsAny() method, but I don't see anything that seems to have that effect.
I would say the existing approach is more readable than your bitwise approach. It says exactly what you mean: if the set contains X, or the set contains Y... Keep it as it is. It's already clean.
If the set becomes larger, you could use:
EnumSet<Foo> valid = EnumSet.of(Foo.X, Foo.Y, Foo.A, Foo.B);
valid.retainAll(enumSet);
if (valid.isEmpty()) {
...
}
But I'd only keep that for larger cases. For two or three options I'd use the longhand form.
You can use the AbstractSet method removeAll (true if any of the elements was found). Obviously, probably you want to do that with a clone of the original set.
If you can't update the set, just create a new one... #assylias is right. An option to that is to just create a new set based on the enum values you want and change/verify accordingly.
public enum ResultingState {
NOT_PERSISTED, PERSISTED, NOT_CALCULATED, CALCULATED;
}
EnumSet<ResultingState> errorsState = EnumSet.of(ResultingState.NOT_PERSISTED, ResultingState.NOT_CALCULATED);
Collection<ResultingState> results = new HashSet<>(phaseResults.values());
boolean containsAny = results.retainAll(errorsState) && results.size() > 0;

Categories