Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

How to find middle value in Java

So I have three doubles for example in Java. They are 1, 2, and 3, as input from the user. How can I set the middle value, as in not max or min, to a variable? Any help would be great, thanks.

2 Answers

Emil Rais
Emil Rais
26,875 Points

If you have three numbers stored in a, b, and c. Then you can do the following to find the middle one and avoid having to deal with a conditional madness.

You could use Arrays.asList(a, b, c) to gather the numbers in a list. You could then sort these with Collections.sort(your list here); the natural ordering of doubles would cause them to be sorted from small to large. You could then look at the middle position of the list, which with 3 numbers (0, 1, 2) would be at index 1.

I'm not too familiar with java so this did not help all that much

Never mind I figured it out, thanks!

Emil Rais
Emil Rais
26,875 Points

That's great; happy coding.

Emil Rais
Emil Rais
26,875 Points

You could also use plain conditional statements. Compare a and b, as well as a and c. If a is larger than both numbers then the middle number is the biggest of b and c. If a is smaller than just one of the numbers then the middle number is a. If a is smaller than both numbers then the middle number is the smallest of b and c. This is the cleanest conditional approach that I can think of.