简体   繁体   中英

Write 1 line If statement using ternary operator in JAVa

Not sure its possible or not. I want to write 1 line if condition statement using ternary operator. Here is my code:

if(preconditionflag.equals("skip")){
System.out.println("Skipping this testcase due to earlier testcase failed");
return flag = "skip";
} else {
flag = "pass";
}

precondflag and flag are String paramaters. Also "else" part is optional to write so please provide code either with else part (flag = "pass") or without it. Thanks in advance.

I assume your actual code looks like this:

if (preconditionflag.equals("skip")){
    System.out.println("Skipping this testcase due to earlier testcase failed");
    flag = "skip";
} else {
    flag = "pass";
}

If not, the answer to your question is already no, because you can't return from a method in one part and not return from a method in the other part of the ternary operation.

The other obstacle speaking against a ternary operation here is the output on STDOUT. Ternary operators don't allow that, but if you really need to you can solve it by creating a helper method:

private void myMethod() {
    ...
    flag = preconditionflag.equals("skip") ?
           showMessageAndReturn("Skipping this testcase due to earlier testcase failed", "skip") :
           "pass";
    ...
}

private String showMessageAndReturn(String message, String retVal) {
    System.out.println(message);
    return retVal;
}

This is an answer following your question exactly but I have difficulties to see an actual use for it in real life.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM