ternary conditional (java) [Solved] | SoloLearn: Learn to code for FREE!


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

🐧Daniel [I use Arch BTW]

15 Answers

New Answer


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


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


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


Kit Delano Cat oh thank you


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


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


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


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


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


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


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


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


java is that weird.


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