英文:
In java, can we use both else and else if in ternary operator and construct 3 conditions in the same statement?
问题
例如,
int number = 10;
number > 9 && number < 100 ? "two digit number" : "not a two digit number";
结果为:two digit number。
但如果数字大于9且小于100,我想要打印出语句:"two digit number",并且在同一语句中,不需要额外的条件代码。
我们可以使用if和elseif语句来实现这一点。但在Java中是否有使用三元运算符的方法来做到这一点呢?
英文:
for example,
int number = 10;
number > 99 && < 1000 ? "three digit number" : "not a three digit number";
result is : not a three digit number.
but i want to print a statement "two digit number" if the number is > 9 and less than 100,
in the same statement without requiring a seperate condition to code.
we can do this with if and elseif statements.
but is there a way to do this with ternary operator in java?
答案1
得分: 0
我认为第二个三元表达式作为“else”条件可以实现你寻找的结果:
int number = 10;
String result = number > 99 && number < 1000 ? "三位数" :
(number > 9 && number < 100 ? "两位数" : "不是两位或三位数");
请注意,与等效的if/else if代码块相比,这可能被认为不太易读,因此这是一种需要谨慎使用的技术。
英文:
I believe a second ternary expression as the "else" condition achieves the result you're looking for:
int number = 10;
String result = number > 99 && number < 1000 ? "three digit number" :
(number > 9 && number < 100 ? "two digit number" : "not a two or three digit number");
Note that this may be considered less readable than the equivalent if/else if block, so this is a technique to use sparingly.
答案2
得分: 0
你可以在三元操作符中使用嵌套的三元操作,如果想要在三元运算符中使用 else-if,但请注意这会降低可读性。
int num = 5;
String result = (num > 9) ? ((num > 99 && num < 1000) ? "三位数" : "两位数") : "个位数";
System.out.println("结果 = " + result);
英文:
You can use Nested Ternary operation if you want to use else-if in ternary operator, but note this is less readable.
int num = 5;
String result = (num > 9)?((num>99 && num<1000)?"Three digit number":"Two digit number"):"Single digit number";
System.out.println("Result = "+result);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论