简体   繁体   English

在 JAVa 中使用三元运算符编写 1 行 If 语句

[英]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.我想使用三元运算符编写 1 行 if 条件语句。 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. precondflag 和 flag 是字符串参数。 Also "else" part is optional to write so please provide code either with else part (flag = "pass") or without it.此外,“else”部分是可选的,因此请提供带有 else 部分(标志 =“pass”)或不带它的代码。 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.这里反对三元运算的另一个障碍是 STDOUT 上的 output。 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.这是完全遵循您的问题的答案,但我很难看到它在现实生活中的实际用途。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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