Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I replace this "if" statement with something else?

beginner coder here. So I have this block of code:

public String doOperation(String s1, String s2) {
    if(s2.compareTo("") == 0) return s1;
    else return s2;
}

Just a rough draft, but essentially I'm saying to return s2 unless it's an empty string, then return s1 instead. Is there any way I can accomplish this without an if statement? For the assignment, I'm not supposed to use if statements, switch statements, while loops, exception handling, or pretty much anything else that is just a sneaky way to get around an "if" statement.

I'm trying to figure out a way to do this through polymorphism but I also don't want to be creating a ton of new things just to accomplish this tiny task. Any ideas/help? Thanks!

like image 622
DrunenAlg Avatar asked Mar 16 '26 08:03

DrunenAlg


2 Answers

You can use ternary operator:

return s2.isEmpty() ? s1 : s2;
like image 173
Vladimir Parfenov Avatar answered Mar 18 '26 20:03

Vladimir Parfenov


Looks like a bit of a brain teaser.. This is awful code, but should do what you want...

return s1.substring(Math.min(s1.length()-1, s1.length() * s2.length()) + s2

So, if s2's length is 0, you'll print s1 starting at position 0, followed by s2, which is empty

If s2's length is not 0, you'll print s1 starting at the last position (i.e. nothing) followed by s2

Oh boy, I feel dirty now :)

like image 42
Miquel Avatar answered Mar 18 '26 21:03

Miquel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!