This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
if(class1.getMethod1().subString(0,1) == "1") && !class1.getMethod1().subString(0,1).equalsIgnoreCase(str1.subString(0,1)(shld be 1 or 2 or 3 )
i.e., String value is 1 or 2 or 3, then I should skip the if condition
I am not able to give
!class1.getMethod1().subString(0,1).equalsIgnoreCase(str1.subString(0,1) == 1 or 2 or 3
Can someone help me with appropriate logic ?
You can use a regex to check if your string starts with 1,2 or 3 (or not)
if(!class1.getMethod1().matches("^(1|2|3).*$")){
//......
}
you don't need substring.
You could store the output of your string in a variable like so:
String myStr = class1.getMethod1().subString(0,1);
And then compare your string with your output by using the equals() method rather than ==
Then you can check multiple conditions by using ||
if(!myStr.equals("1") || !myStr.equals("2") || !myStr.equals("3")) {
// Run conditional code...
}
This will make it so the code in the if statement will only run if the output of myStr is not 1, 2 or 3, thus the if statement will be skipped if the string is 1, 2 or 3
Having several cases that should not be processed follows the pattern !A && !B && !C.
String name = class1.getMethod1();
if (!name.startsWith("1") && !name.startsWith("2") && !name.startsWith("3")) {
...
}
I would create util class with method like this:
boolean isAny(String parameter, String ... values) {
for(String value : values) {
if(parameter.equals(value) {
return true;
}
}
return false;
}
You could use it in if statement like this:
if(!YourUtil.isAny(class1.getMethod1().subString(0,1), "1", "2", "3")) {
//
}
It's nice because you don't have redundant || what could make Sonar happy.
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 2 years ago.
I am trying to have a text-box populate with X if another text-box has a certain value, else Y. However, it's populating with X or Y seemingly randomly. d4 is my button, d4result is where it populates the result, d4txt1 is where I want to see a 1 or 0, depending.
d4.setOnClickListener {
if (d4result.text.toString() == "1") {
d4txt1.text = "1"
} else {
d4txt1.text = "0"
}
val rand = Random().nextInt(4) + 1
d4result.text = rand.toString()
}
So if d4result is populated with 1, I want d4txt1 to populate with 1, otherwise it should be zero. But when I try it, I get 1 or 0 and I can't notice a pattern as to when/why.
Use equals instead of ==. == operator will return true only if two object reference it is comparing represent exactly same object otherwise "==" will return false.
d4.setOnClickListener {
if (d4result.text.toString().equalsIgnoreCase("1")) {
d4txt1.text = "1"
} else {
d4txt1.text = "0"
}
val rand = Random().nextInt(4) + 1
d4result.text = rand.toString()
}
Java is tricky about that. The == operator compares the two object pointers, not their values. It's fine for integers and floats but almost never useful for strings.
Instead use the .equals() method or the .equalsIgnoreCase() method:
if (d4result.text.toString().equalsIgnoreCase("1")) { ...
This question already has answers here:
Java ternary (immediate if) evaluation
(3 answers)
Closed 7 years ago.
I recently got help writing a statement checking if input text was blank or only whitespace. I got it working but do not really understand the code since its too advanced refactoring for me. Could someone please translate this to more basic code?
name = name == null ? "" : name.trim();
Your code is similar to:
String name = //your input
if(name==null) {//if name si null
name = "";//assign empty string
} else {
name = name.trim(); //remove leading and trailing whitespace
}
The if else is replace with "? :" operator
The thing you are seeing is a "ternary operator". It follows this syntax:
boolean ? ifTrue : ifFalse
Ternary operators do not work quite like if/else statements: They provide you with a value (like 3 + 4).
So in this example, you set name to the result of the following ternary expression:
is name null? -+- true --> ""
|
+- false -> name.trim() (this function removes whitespace at
the beginning and at the end of the string)
You could also write:
public static String parseName(String name)
{
if (name == null)
return "";
//else (else not neccesary here)
return name.trim();
}
// in some block...
name = parseName(name);
if name is equal to null it will be equal to "";
else it will be equal to name.trim()
name = name == null ? "" : name.trim();
that means
String name;
//You performed some processing here, your logic.
if(name==null){
name="";
}
else{
name=name.trim();
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I have an issue with the if/else function in my Java code (Android / Eclipse).
When I'm in debug mode, checkGender is equal to "M", but goes directly to "else" instruction and considers that 'checkGender' is not equal to "M". I don't understand why? For information, searcher.getString("Gender") takes information from MySQL.
String checkGender = "";
checkGender = searcher.getString("Gender");
if(checkGender == "M")
{
bGenderM.setChecked(true);
}
else
{
bGenderF.setChecked(true);
}
Debug info :
checkGender = "M" (id=8300460...)
value[0] = M
If I replace "searcher.getString("Gender");" by a simple "M", it works.
Thanks for your help.
Tom
Actually best would be to do it "Yoda-style"
if("M".equals(checkGender)) {
//code for male
} else {
//code for female
}
That way you avoid potential NullPointerException for the case that checkGender == null
Use equals() method instead of == for String comparison.
if(checkGender.equals("M")) {
bGenderM.setChecked(true);
} else {
bGenderF.setChecked(true);
}
OR, use equalsIgnoreCase() method and it better...
if(checkGender.equalsIgnoreCase("M")) {
bGenderM.setChecked(true);
} else {
bGenderF.setChecked(true);
}
This question already has answers here:
String.equals() with multiple conditions (and one action on result) [duplicate]
(7 answers)
Closed 2 years ago.
I was wondering how I can compare multiple strings in one line. I tried using the || but it doesn't work for booleans or strings. this is what my code is like:
}else if(question != "a" || "b") {
System.out.println("Sorry that isn't an A or a B");
For those who marked it duplicate, I checked over 200 questions here on stack overflow, and none worked. The one #Chrylis posted actually didn't help. they were just asking about the difference in == and .equals()
First of all, don't use == for strings. You'll learn why later. You want to compare strings by their contents, not where they are in memory. In rare cases a string of "a" could compare false to another string called "a".
Second, split it up so you are performing boolean logic on the comparison results:
else if(!(question.equals("a") || question.equals("b")) {
You can try using Arrays.asList():
else if (!Arrays.asList("a", "b").contains(question)) {
...
}
Two things wrong: You can't just specify multiple values with || (or &&) like that. You need to specify both the left side and the right side explicitly each time.
Second, use equals to compare String values, not the == (or in this case !=) operators. == compares two object references to see if they are the same object.
} else if (!("a".equals(question) || "b".equals(question)))
Or an alternative is to make a temporary List and use contains, which might be clearer for longer lists of things to test:
} else if (!Arrays.asList("a", "b").contains(question))
String[] options = {"a", "b"}; // Must be sorted.
if (java.util.Arrays.binarySearch(options, question) < 0) {
System.out.println("Sorry that isn't an A or a B");
}
Alternatively (assuming your strings don't contain |:
if ("a|b".indexOf(question) == -1) {
System.out.println("Sorry that isn't an A or a B");
}
As an aside, you should use equals for objects not ==
To answer your question, you have to repeat the equals call on both sides of the ||
}else if( ! (question.equals("a") || question.equals("b")) ) {
}else if( !(question.equals("a") || question.equals("b")) {
System.out.println("Sorry that isn't an A or a B");
You can't do NOT equals a OR b
You have to do NOT(equals a OR equals b)
Secondly, you are comparing strings with !=, but you should be comparing strings using the .equals(String) method. This has been said millions of times, but: == and != are comparing object references, whereas .equals(String) is comparing String values.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I wanna ask you ,
do you have a solution for this question (if statement) or where is the error ?
String z = input.nextLine() ; //i want from the user value of z .
if (z ==( "Y" || "y" ))
{
statement ...
}
else if (z==("N" || "n" ))
{
statement ...
}
How to write a condition for if when the condition of String in Java ?
you can say
if(z.equalsIgnoreCase("y")){
//code...
}
You are probably looking for equalsIgnoreCase. You can use it like
if (z.equalsIgnoreCase("Y")){//do your job
use equals().
== does reference equality which you don't want.
So use equals() as you want to check the content equality.