-2
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 ?

Stunner
  • 12,025
  • 12
  • 86
  • 145
sahana
  • 601
  • 5
  • 12
  • 33
  • 9
    Do not use `==` to compare strings in Java; use `equals()` instead. See: [How do I compare strings in Java?](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Jesper Nov 02 '17 at 10:58
  • btw. that `class1.getMethod1().subString(0, 1)` is craving to be extracted into a local variable, thus simplifying the condition by 50 characters. – xtofl Nov 02 '17 at 11:05
  • 1
    The logic is wrong, look : IF (first character is 1) AND (first character is NOT 1 or 2 or 3). Also note that it is probably overkill to ignore case of strings representing numbers. `1` to lowercase is still `1`, not _nearly_ `1` . – Arnaud Nov 02 '17 at 11:05
  • use `||`to mean "or" please – HbnKing Nov 02 '17 at 11:08

4 Answers4

2

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.

Eritrean
  • 15,851
  • 3
  • 22
  • 28
0

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

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
0

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")) {
    ...
}
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
0

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.

dzuma
  • 171
  • 5
  • 17