Reputation: 628
How can i write this if/else expression in short form using ternary operator ?
int value1 = 5,value2 = 0;
if (value2 == 0) {
} else {
value1 = value1 / value2;
}
Upvotes: 0
Views: 5581
Reputation: 10126
Use ternary operator
value1 = value2 == 0 ? value2 : value1 / value2;
Upvotes: 0
Reputation: 333
ternary operator syntax is
condition?true statement:false satatement;
for your code use
value2 == 0? : value1 / value2;
Upvotes: 0
Reputation: 30676
the simplest way is just invert condition and using if
statement only:
if(value2 != 0) {
value1 = value1 / value2;
}
Upvotes: 3
Reputation: 30809
You don't need to take any action on value
if value2
is 0, so you can write a ternary operator that assigns value1
to value1
if value2
is 0, and value1 / value2
otherwise, e.g.:
value1 = value2 != 0 ? value1 / value2 : value1;
Upvotes: 3