Green_Sam - 1 year ago 87
Java Question

# Java, second maximun number without arrays or loops

I'm trying to create a Program that returns the second maximum number without using arrays or loops. It seems impossible, I thought about calculating the max number and then create a new method without the number that's the maximum but I don't know how to do it.

``````public class Program {

public static double max10(double n1, double n2, double n3, double n4,double n5, double n6, double n7, double n8, double n9, double n10) {

double r1,r2,r3,r4,r5,r6,r7,r8,r9;

r1= max2(n1,n2);
r2= max2(n3,n4);
r3= max2(n5,n6);
r4= max2(n7,n8);
r5= max2(n9,n10);

r6= max2(r1, r2);
r7= max2(r3, r4);

r8= max2(r6, r7);
r9= max2( r8, r5 );

return max2( r9, r5 );

}

public static double max2 (double n1, double n2) {

return n1>=n2 ? n1 : n2;
}

public static void main(String[] args) {

System.out.println(max10(1,2,3,4,5,6,7,8,9,10)==10);
System.out.println(max10(1,2,3,4,5,45,7,8,9,10)==45);
System.out.println(max10(1,2,3,4,5,6,7,8,10,10)==10);

}
}
``````

Are there any tricks?

1. Find the max number using the method you were using above,
2. Instead of returning that max number, you then call a new method, max9, with all the numbers from the original minus the maximum value

``````public static double getSecondMaxValue(double n1, double n2, double n3, double n4,double n5, double n6, double n7, double n8, double n9, double n10){

double maxValue = max10(double n1, double n2, double n3, double n4,double n5, double n6, double n7, double n8, double n9, double n10)

double secondMaxValue = 0.0;

if(maxValue == n1)
secondMaxValue = max9(double n2, double n3, double n4,double n5, double n6, double n7, double n8, double n9, double n10);
else if (maxValue == n2)
secondMaxValue = max9(double n1, double n3, double n4,double n5, double n6, double n7, double n8, double n9, double n10);
else if (maxValue == n3)
secondMaxValue = max9(double n1, double n2, double n4,double n5, double n6, double n7, double n8, double n9, double n10);
...
...
else if (maxValue == n10)
secondMaxValue = max9(double n1, double n2, double n3, double n4,double n5, double n6, double n7, double n8, double n9);

return secondMaxValue;

}

public static double max9(double n1, double n2, double n3, double n4,double n5, double n6, double n7, double n8, double n9) {

double r1,r2,r3,r4,r5,r6,r7,r8,r9;

r1= max2(n1,n2);
r2= max2(n3,n4);
r3= max2(n5,n6);
r4= max2(n7,n8);
r5= n9;

r6= max2(r1, r2);
r7= max2(r3, r4);

r8= max2(r6, r7);
r9= max2( r8, r5 );

return max2( r9, r5 );
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download