Construct0r Construct0r - 1 year ago 63
Java Question

How to Pass This Test Case?

I'm creating the program that determines the largest and smallest number is a series of numbers entered by the user. I've created several tests cases for my code and they all work out, but it fails the most simple test case. When the user inputs a single number. For instance, if the user sets the terminating value to be 25, then enters -1, and finally enters the terminating the value, the output should be
Largest: -1 and Smallest: -1. However, my code will output Largest: 0 and Smallest: -1 -- I why this happens (because I initialized the max value to be 0 before running the loop), but how can I fix this?

Here's my code...

Scanner scan = new Scanner(;

// Declaration variables
double min;
double max = 0;

System.out.println("Enter terminating number: ");
double terminator = scan.nextDouble();

System.out.println("Enter a number: ");
double num = scan.nextDouble();
min = num;

if (num == terminator) {
System.out.println("There must be one number in the list.");
// break;
} else {
while (num != terminator) {
num = scan.nextDouble();

if ((num < min) && (num != terminator)) {
double temp = min;
min = num;
max = temp;
} else if ((num > min) && (num != terminator)) {
max = num;
} else {
max = min;
System.out.println("Largest: " + max);
System.out.println("Smallest: " + min);

Answer Source

Instead of initializing max = 0, do max = num just like you already do with min.

It's not clear why you're initializing max differently from min; when a single number has been entered, it's both the minimum and the maximum. Right now, the only code that modifies max is within the loop that reads numbers beyond the first, so the first number has no effect on it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download