I have a following problem - if else statements do not work in JSP, and to be honest I have no idea why. Basically I try to change the placeName depending on what number is stored in a string called place. After printing the values in the browser I can see the value is not changed. I am sure it is something simple but... Maybe some one had similar problem before?
<%
//requests the strings sent by previous page
String year = request.getParameter("year");
String place = request.getParameter("place");
out.print(year);
out.print(place);
String year2 = request.getParameter("year2");
String place2 = request.getParameter("place2");
//out.print(year2);
//out.print(place2);
if (place == "1")
{
placeName = "Belmullet";
}
else if (place == "2")
{
placeName = "Birr";
}
...more statements here...
else if (place == "15")
{
placeName = "Shannon airport";
};
%>
change the if condition:
if (place == "1") {
}
by
if ("1".equals(place)) {
}
and the same way for the other if conditions.
This SO question may helps you to learn the difference between == and equals().
It's because you're comparing Strings using ==. Instead, use the .equals() method.
The == operator tests to see if two object references refer to the exact same instance of an object.
The .equals() tests to see if the two objects being compared to each other are equivalent.
Related
I am comparing two strings in if else block..if it is true if block should be executed and if it is false else block should execute..but my code is always executing else block for both true & false condition..here is my code
if(deckey==keystr)
{
.
.
}
else
{
System.out.println("your unauthorised person");
System.exit(0);
}
my deckey is containing string value abc123 and for keystr i am getting the value from this which is also abc123(i am getting through arraylist)..
ArrayList<Integer> listfkey= new ArrayList<Integer>();
String keystr=" ";
for (int i = 0; i < listfkey.size(); i++) {
dech=(char)listfkey.get(i).intValue();
keystr+=dech;
}
please help me out..
Strings need to be tested for equality using the .equals method:
deckey.equals(keystr)
Not the == operator, which tests if two string instances are the same:
deckey==keystr
primatives are a different matter, but with Java objects, == will only return true if the object is being compared to itself (same memory location). For Objects, use the equals method or the Comparator interface
== is use for compare memory location, it will be right on some primitive data
String is object, so for compare it we need to use .equals() method
It come from Comparator
I get a string form a list and try to compare it with some strings in the values and then do some stuff
for(int i=0; i<sizeOfList; i++){
String LIST_TITLE;
LIST_TITLE = list_title.get(i); //the List list_title includes some strings
if(LIST_TITLE.equals(R.string.percentbattery)) {
//do stuff
Log.d("EQUAL!","" + LIST_TITLE);
} else if(LIST_TITLE.equals(R.string.screenrecorder) == true) {
//do stuff
Log.d("EQUAL!","" + LIST_TITLE);
} else if(LIST_TITLE.equals(R.string.eightsms) == true) {
//do stuff
Log.d("EQUAL!","" + LIST_TITLE);
} else {
// do stuff
Log.e("TITLE NOT EQUAL","" + LIST_TITLE);
}
}
If I compare my LIST_TITLE with the (R.string. ...) in my Logcat they are equal, but I get only the "TITLE NOT EQUAL" Log from the else statement.
Is there another way to compare these strings? the "==" method also don't work.
R.string.percentbattery is not a String, it's an Integer that is the ID to reference the string.
what u want is:
LIST_TITLE.equals(context.getResources.getString(R.string.percentbattery))
LIST_TITLE.equals(R.string.percentbattery)
This is incorrect, because you're trying to compare string with resource ID
You should get the string from resource first:
LIST_TITLE.equals(getResources().getString(R.string.percentbattery))
R.string.xxx is an int. You need to get the String from that res
Something like
if(LIST_TITLE.equals(getResources().getString(R.string.percentbattery)))
This is assuming you have Activity Context available. Otherwise, you would need to add a Context variable in front of getResources()
R.string.some_id is just an integer by which you can get the String from the resources.
So in order to compare Strings correctly in you case you have to do:
String precentBattery = getResources().getString(R.string.percentbattery);
if (LIST_TITLE.equals (percentBattery)) ...
I have a doubt regarding checking null condition.For eg :
if(some conditon)
value1= value; //value1 is string type
else
value1= "";
Similarly some 4 other string value has similar condition.
What i need is i want to check whether all those 5 string value is null or not,Inorder to do some other specific part.
i did it like this
if(value1 == null)
{
}
but the pgm control didnot entered the loop eventhough value1="".
then i tried
if(value1 ==""){
}
this also didnt worked.
Cant we check null and "" value as same??
can anyone help me??
If you want to check is a String is null, you use
if (s == null)
If you want to check if a string is the empty string, you use
if (s.equals(""))
or
if (s.length() == 0)
or
if (s.isEmpty())
An empty string is an empty string. It's not null. And == must never be used to compare string contents. == tests if two variables refere to the same object instance. Not if they contain the same characters.
To check both "is not null" and "is not empty" on a String, use the static
TextUtils.isEmpty(stringVariableToTest)
It looks like you want to check wether a String is empty or not.
if (string.isEmpty())
You can't check that by doing if (string == "") because you are comparing the String objects. They are never the same, because you have two different objects. To compare strings, use string.equals().
When you are working on String always use .equals.
equals() function is a method of Object class which should be overridden by programmer.
If you want to check the string is null then if (string.isEmpty()) else you can also try if (string.equals(null))
You can use:
we can check if a string is empty in 2 ways:
if(s != null && s.length() == 0)
if(("").equals(s))
prefer below.
String str;
if(str.length() > 0)
{
Log.d("log","str is not empty");
}
else
{
Log.d("log","str is empty");
}
this is my first so I'll try to add as much info as possible so I don't get yelled at. :-)
What I am trying to do is I have 2 variables that grab text from 2 fields and take only the first character from each and assign it to those values.
This is the code that I use to get the strings. They are 2 separate calls as you would.
try { var_ContactSurname = var_ContactSurname.substring(0,1);
}
catch (Exception e){
}
I have the above again with a different variable. Now to this point it does what I want. It grabs the first letter from the fields and assigns it to the variables.
So at this point I have two variables (say with an example charater of D and R).
var_ContactSurname = R
var_ContactLicenceNumber = D
What I want to do is compare those two variables and if they match I want to return a value of TRUE, else FALSE if they don't match.
That value has to be a string as well and be assigned to a new variable called var_ContactValidate.
if (var_ContactLicenceNumber.toLowerCase().equals()var_ContactSurname.toLowerCase()){
var_ContactValidate == "TRUE";
}
else {
var_ContactValidate == "FALSE";
}
No you may notice that there might be some code missing. I am using a rules engine that does a lot of the functions for me. I can use raw Java code to do other things (like this compare)...but that's the compare that I am having a problem with.
Any ideas for that compare would be greatly appreciated.
Thanks.
i would use the String method equalsIgnoreCase()
to assign a value to a field, use a single =, not double (==).
if (var_ContactLicenceNumber.equalsIgnoreCase(var_ContactSurname){
var_ContactValidate = "TRUE";
}
else {
var_ContactValidate = "FALSE";
}
check it
In addition to what already said - a simpler & more elegant version (without the if condition) could be:
var_ContactValidate = Boolean.toString(
var_ContactLicenceNumber.equalsIgnoreCase(var_ContactSurname))
.toUpperCase();
Change your whole piece of code to:
if (var_ContactLicenceNumber.equalsIgnoreCase(var_ContactSurname)){
var_ContactValidate == "TRUE";
}
else {
var_ContactValidate == "FALSE";
}
This combines the case insensitivity that you want, and passes through the second string as an argument of the .equalsIgnoreCase function.
Also, I am not sure what you are trying to do with the line:
var_ContactValidate == "TRUE";
If you want to assign var_ContactValidate to "TRUE" then use a single equals sign '=' as a double equals '==' compares the values instead. You may also considering using a boolean rather than a string in this case.
Here is an implementation that also checks for null values and empty Strings:
public class SurnameAndLicenseValidator {
public static void main(String[] args) {
// FALSE
validateSurnameAndLicense(null, "jb78hq");
validateSurnameAndLicense("Johnson", null);
validateSurnameAndLicense(null, null);
validateSurnameAndLicense("", "jb78hq");
validateSurnameAndLicense("Johnson", "");
validateSurnameAndLicense("", "");
validateSurnameAndLicense("johnson", "xb78hq");
// TRUE
validateSurnameAndLicense("Johnson", "jb78hq");
validateSurnameAndLicense("johnson", "jb78hq");
}
private static String validateSurnameAndLicense(String surname,
String license) {
String result;
if (surname != null
&& surname.length() > 0
&& license != null
&& license.length() > 0
&& Character.toUpperCase(surname.charAt(0)) == Character
.toUpperCase(license.charAt(0))) {
result = "TRUE";
} else {
result = "FALSE";
}
System.out.println(surname + " " + license + " " + result);
return result;
}
}
The main method is used as a unit test here. You might want to extract a real JUnit test from it, if you are into that kind of thing.
Hello everybody I have a question:
I have a array
String[] parte
and I need of the first value of the array so I did:
String verifica = parte[0] // It can be N (for Name) L (for List) and E (for Error)
Why if I run this code and I know that "verifica" is L
if (verifica == "L") { //If code
} else { //Else code
}
it returned to me always the Else code
ThankYou sooooo much
-Matteo
Comparing Strings in Java must be done with String.equals():
if (verifica.equals("L")) { //If code
What you were trying to do was comparing two distinct objects, and not their contents.
You need to use:
if (verifica.equals("L")) { //If code
} else { //Else code
}
instead of '=='. '==' in Java checks for object identity in memory, where the functionality you're needing here is to compare String values. Took me experiencing this error to realize the difference (I come from a C# background) in Java as well.
Use the equals operator for strings:
if (verifica.equals("L"))
You want if (verifica.equals("L")) or if (verifica.compareTo("L") == 0). == is not a reliable operator for comparing strings.