-1

I'm using java8. I made the code below from the sample. I want to refactoring this, but I don't know how. Let me know if you have any good ideas.

Add Description : There was some error in coding, so I corrected it.


String returnStr = "";
if(a != "" && b != "" && c != ""){
    returnStr = "1";
}else{
    if(a != "" && b != ""){
        returnStr = "2";
    }else if(a != "" && c != ""){
        returnStr = "3";
    }else if(b != "" && c != ""){
        returnStr = "4";
    }else{
        if(a != ""){
            returnStr = "5";
        }else if(b != ""){
            returnStr = "6";
        }else if(c != ""){
            returnStr = "7";
        }else{
            returnStr = "8";
        }
    }
}

return returnStr;
her1440
  • 11
  • 2
  • 8
    [Do not compare `String`s with `==`](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Turing85 Aug 24 '20 at 20:23
  • 3
    What is `int return = "";` supposed to mean? – Hulk Aug 24 '20 at 21:06
  • Please read about what's on-topic in the [help/on-topic]. Code review is off-topic, but you might want to check out our sister site [codereview.se]. Please make sure to read _its_ on-topic page, take its tour, and read its How to Ask page before posting there. – ChrisGPT was on strike Aug 25 '20 at 00:31

2 Answers2

1

Construct an int from the 3 bits effectively implied by the "emptiness" checks:

int i = (a != "" ? 4 : 0) | (b != "" ? 2 : 0) | (c != "" ? 1 : 0);

(Yes, you should be using equals, or isEmpty(), instead of !=. That's not really the point).

This gives a number in the range 0 to 7, inclusive.

Construct an 8-element list or array, where the number is the value you want to return.

Then, use i from above to select an element from that list/array:

return list.get(i);  // or array[i]
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
0

You don't need all those else and you could make it more concise and clear like this:

if(a != "" && b != "" && c != "") return 1;
if(a != "" && b != "") return 2;
if(a != "" && c != "") return 3;
if(b != "" && c != "") return 4;
if(a != "") return 5;
if(b != "") return 6;
if(c != "") return 7;
return 8;
Loris Securo
  • 7,538
  • 2
  • 17
  • 28