+8

ternary conditional (java) [Solved]

Hey, Why is it printing "5.0"? Isn't it suppose to print "5"? Since I added "(int)" before it? https://code.sololearn.com/cJL9g3CxZO3G/#java Thank you! [Solved] https://code.sololearn.com/copwkZGEja04/#java

11/8/2019 9:46:57 PM

Mr. 🍊range

17 Answers

New Answer

+4

Alright, so this is pretty redundant... but it works https://code.sololearn.com/cuuwxLGx1Zb8/?ref=app

+6

I'm using a keyboard called "ninja pro" which all the keys are invisible lol Spelling mistake happens 😉 Thanks for your answer 😎👍

+5

Comparing floats and doubles using == operator is not recommended. So kindly read the Oracle documentation once, may be you will get an idea.

+4

Mr. 🍊range It's tried not tired 😁. Btw you are comparing double with int so it will be false and return will be 5.0

+4

According to the Java Language Specification §15.25, table 15.25-B: If the second argument is of type int and the third of double, binary numeric promotion int -> double applies. So, the resulting type of the ternary is 'double'. https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.25

+4

Kit Delano Cat oh thank you

+4

voja yes but in here both true and false statement have int... what if I used 5.8? It will print "5" My goal is : If a = 5.0 the output I want is "5" NOT "5.0" But If a = 5.8 the output I want is "5.8" Using thernary conditions... Is it even possible? LOL

+4

Mr. 🍊range This works: double a = 5.0; if((int)a - a == 0){ System.out.println((int)a); }else{ System.out.println(a); }

+3

Kit Delano Cat So is there is any possible way make it print "5"? In ternary conditional?

+3

No problem LOL I'm trying to find it for 4 hrs... Still finding😔 THANK YOU FOR YOUR HELP

+2

I tired switching (int) to the false side... Still printing "5.0"

+2

Yes, if you make second argument int too: System.out.println((a == (int)a) ? (int)a : (int)a);

+2

The type of the ternary is determined at compile time. The resulting type chosen will be such that least damage is done. As long as one argument is a floating point type, the result will be floating point (even if losses occur)

+2

double a = 5.0; System.out.println((a == (int)a) ? String.valueOf((int)a) : a); Shorter and works fine.

+1

Mr. 🍊range yeah, now I get what you want... I guess I am a bit tired.. 😔

+1

java is that weird.

0

كج٩