-3

I have three if conditions something like below

if ((class1.getMethod1().subString(0,1) == "1") && !class1.getMethod1().subString(0,1).equalsIgnoreCase(str1.subString(0,1))
if ((class1.getMethod1().subString(0,1) == "2") && !class1.getMethod1().subString(0,1).equalsIgnoreCase(str1.subString(0,1))
if ((class1.getMethod1().subString(0,1) == "3") && !class1.getMethod1().subString(0,1).equalsIgnoreCase(str1.subString(0,1))

All the if conditions are gonna do same stuff. Is there anyway I can avoid repeating these many if conditions and make it in a single line ?

sahana
  • 601
  • 5
  • 12
  • 33
  • maybe make a method call out of it? `if(myCondition(class1, "1")){}` – Lino Nov 02 '17 at 10:34
  • How about a `switch` statement? – S.L. Barth is on codidact.com Nov 02 '17 at 10:35
  • 4
    get the substring first and do the comarison on the substring (`String substring = class1.getMethod1().subString(,01); ... substring.equals("1"); ...`). And [never compare objects via `==` unless you exactly know what you are doing](https://stackoverflow.com/questions/767372/java-string-equals-versus). – Turing85 Nov 02 '17 at 10:35
  • 1
    This Kind of question is about code Review and should be ask at [codereview.SE] – Jens Nov 02 '17 at 10:35

1 Answers1

2

Actually you have different == check for the subString to match with either case "1", "2" or "3". So you can write like this

if(((class1.getMethod1().subString(0,1) == "1") 
  || (class1.getMethod1().subString(0,1) == "2") 
  || (class1.getMethod1().subString(0,1) == "3"))
  && !class1.getMethod1().subString(0,1).equalsIgnoreCase(str1.subString(0,1))

The above will make it in single line

Lukas
  • 1,320
  • 12
  • 20
Subash J
  • 2,028
  • 3
  • 13
  • 27