-1

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?

M. Justin
  • 14,487
  • 7
  • 91
  • 130
sravanTG
  • 574
  • 5
  • 9
  • 1
    See https://stackoverflow.com/questions/5574058/how-to-check-if-an-integer-is-in-a-given-range for other ideas. – GhostCat Oct 20 '20 at 08:01
  • 1
    Nesting ternary if-else statements is quickly becoming unreadable. I would advise you not to do so. – MC Emperor Oct 20 '20 at 08:16

2 Answers2

0

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.

M. Justin
  • 14,487
  • 7
  • 91
  • 130
  • as i can see u wrote a complete different statement for two digit expression.but is there a wayto adjust this as a three word statement after the "three digit number" in te first line? – sravanTG Oct 20 '20 at 06:40
  • @sravanTG No, there's no ternary-style expression with more than three parts. – M. Justin Oct 21 '20 at 14:49
0

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);

Praveen L
  • 79
  • 1
  • 1
  • 6