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?
CodePudding user response:
totnum
is a b c
. Find the min
, find the max
. Subtract from totnum
that is your second highest value. Also, prefer to declare your variables when you initialize them. Don't perform integer math to find the average. And you could use printf
to format. Like,
int high = 100;
int low = 75;
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);
int totnum = a b c;
System.out.printf("The random grades are: %d, %d, %d%n", a, b, c);
System.out.println("====================================================");
int highest = Math.max(a, Math.max(b, c));
int smallest = Math.min(a, Math.min(b, c));
int second = totnum - highest - smallest;
System.out.printf("The highest number is: %d%n", highest);
System.out.printf("The second number is: %d%n", second);
System.out.printf("The lowest number is: %d%n", smallest);
System.out.printf("The average of three numbers is: %.2f%%%n", totnum / 3.0);
Example output
The random grades are: 87, 93, 89
====================================================
The highest number is: 93
The second number is: 89
The lowest number is: 87
The average of three numbers is: 89.67%
CodePudding user response:
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: