patternjavaMinor
Comparing multiple arguments and returns the smallest argument
Viewed 0 times
smallestargumentsthecomparingargumentreturnsmultipleand
Problem
I want to see if anyone knows how to optimize the code below:
public class smallestTest
{
public static void main(String[] args)
{
double resultSmallest = smallest(2.5, 3.5, 4.5);
System.out.println("The smallest number out of 2.5, 3.5, and 4.5 is: " + resultSmallest);
}
/**
Computes the smallest of three variables
@param x, y, z
@returns smallestNumber
*/
public static double smallest(double x, double y, double z)
{
double smallestNumber = 0;
if ( x < y && x < z)
{
smallestNumber = x;
}
else if (y < x && y < z)
{
smallestNumber = y;
}
else if (z < x && z < y)
{
smallestNumber = z;
}
return smallestNumber;
}
}Solution
You can use something called Varargs that was introduced in java 5.
It is used in method declarations to declare arguments as an array.
You can adapt this to your program by doing the following:
You can then call this with as many
It is used in method declarations to declare arguments as an array.
public void myMethod(double... doubleArray) {
}
public void callMyMethod() {
myMethod(1.2, 4, 2, 1); // all those are put into a double[]
}You can adapt this to your program by doing the following:
public static double smallest(double... vals) {
// must pass at least 1 argument. You could also return Double.NaN or something
if(vals.length == 0) throw new IllegalArgumentException("smallest must be passed at least 1 value.");
// start with the first value as the smallest
double smallest = vals[0];
for(int i=1;i<vals.length;i++) {
// see if this ones smaller than our stored smallest
if(vals[i] < smallest) {
smallest = val[i];
}
}
return smallest;
}You can then call this with as many
double values as you like.Code Snippets
public void myMethod(double... doubleArray) {
}
public void callMyMethod() {
myMethod(1.2, 4, 2, 1); // all those are put into a double[]
}public static double smallest(double... vals) {
// must pass at least 1 argument. You could also return Double.NaN or something
if(vals.length == 0) throw new IllegalArgumentException("smallest must be passed at least 1 value.");
// start with the first value as the smallest
double smallest = vals[0];
for(int i=1;i<vals.length;i++) {
// see if this ones smaller than our stored smallest
if(vals[i] < smallest) {
smallest = val[i];
}
}
return smallest;
}Context
StackExchange Code Review Q#82210, answer score: 3
Revisions (0)
No revisions yet.