Skip to content
Advertisement

Find the highest, second highest, and lowest of three random generated numbers without using conditional statements

As a 1st year college IT student, I have a Java assignment where I must display three random generated numbers and order them highest, second highest, lowest. The challenge given by our professor is to not use any conditional statements or arrays.

Here is the code:

import java.text.DecimalFormat;
import java.util.Scanner;
import java.util.Random;
public class Main {
  public static void main(String[] args) {
    DecimalFormat dcf = new DecimalFormat("0.00");
    Scanner sc = new Scanner(System.in);
    Random rand = new Random();
    int high, low, totnum;
    double NumAvr;
    
    high = 100;
    low = 1; 
     
    int a = (int)(Math.random()*(high-low+1)+low);  
    int b = (int)(Math.random()*(high-low+1)+low);  
    int c = (int)(Math.random()*(high-low+1)+low);   
    
    totnum = a + b + c;
    NumAvr = totnum / 3;
    
    System.out.println("The random grades are: "+a+", "+b+", "+c);
    System.out.println("====================================================");
    System.out.println("The highest number is: "+ Math.max(a, Math.max(b, c)));
    System.out.println("The second number is: "+ Math.max(b, c));
    System.out.println("The lowest number is: "+ Math.min(a, Math.min(b, c)));
    System.out.println("The average of three numbers is: "+dcf.format(NumAvr)+"%");
     

    //MathClass.java
  }
}



The problem I am facing is that I am struggling to get the “in-between” value of the highest and lowest. Is there any “in-between” variable for me to get the second highest without using any conditional statement or array?

Answer

You can do this:

int max=Math.max(a, Math.max(b, c));
int min=Math.min(a, Math.min(b, c));
int inBetween=totnum - max -min:
Advertisement