Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Finding the maximum between 3 values?  RSS feed

 
Sam Bluesman
Ranch Hand
Posts: 191
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I know that i can use Math.max(a,b) to find the maximum of two values called a and b. However, if i have a third, it wont let me. What is the best way to do this?

Thanks
 
praveen Shangunathan
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Math.max((Math.max(a,b)),c)
 
Stuart Ash
Ranch Hand
Posts: 637
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by praveen Shangunathan:
Math.max((Math.max(a,b)),c)


Why, it's simplicity itself!
 
fred rosenberger
lowercase baba
Bartender
Posts: 12542
48
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
but that can get ugly if you start having more than 3... what are you going to do if you have 50? or 1000?

the solution would probably depend on how you are storing them, but i'll leave it as an exercise for you to think about...
 
Henry Wong
author
Sheriff
Posts: 23283
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am surprised that in Java 5, they didn't reimplemented the max() method to use varargs.

Henry
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, a varargs max() might be something you want to make on your own. I was surprised Sun didn't do that; it's another thing I miss from REXX.
 
Rob Spoor
Sheriff
Posts: 21092
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by fred rosenberger:
but that can get ugly if you start having more than 3... what are you going to do if you have 50? or 1000?

the solution would probably depend on how you are storing them, but i'll leave it as an exercise for you to think about...
If you have that many values to get the maximum for you should really get a collection / array and iterate over it. If you write that many by hand you're insane.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!