How to find the biggest, second biggest and third biggest number in an
array, then display their sequence location?
I have this so far:
public static void highV()
{
KeyboardReader reader = new KeyboardReader();
int numVal = 0;
while (numVal < 3) // Makes sure 3 or more numbers are entered
{
numVal = reader.readInt("How many values would you like to enter
(3 or more): ");
if (numVal < 3)
{
System.out.println("Invalid Entry");
}
}
int[] dval = new int[numVal];
int i;
int j;
int k;
int a;
int high = 0;
int sec = 0;
int thr = 0;
System.out.println();
for (i = 0; i < dval.length; i++) // Reads in numbers and stores them
in an array
{
dval[i] = reader.readInt("Enter value number " + (i + 1) + ". ");
}
System.out.println();
System.out.print("List of values: ");
for (j = 0; j < dval.length; j++)// Prints out a list of values
{
if (j == (dval.length)-1)
{
System.out.println(dval[j]);
}
else
{
System.out.print(dval[j] + ", ");
}
}
System.out.println();
System.out.println("There was a total of " + dval.length + " numbers
entered.");
System.out.println();
for (k = 0; k < dval.length; k++) // Determines the highest second
highest and third highest numbers
{
if (dval[k] > high)
{
int oldSec = sec;
sec = high;
thr = oldSec;
high = dval[k];
}
else if (dval[k] > sec)
{
thr = sec;
sec = dval[k];
}
else if (dval[k] > thr)
{
thr = dval[k];
}
}
for (a = 0; a < dval.length; a++) // Determines sequence location of
first second and third highest numbers
{
if (dval[a] == high)
{
high = a+1;
}
if (dval[a] == sec)
{
sec = a+1;
}
if (dval[a] == thr)
{
thr = a+1;
}
}
System.out.println("The highest number was in sequence #: " + high);
System.out.println("The second highest number was in sequence #: " +
sec);
System.out.println("The third highest number was in sequence #: " + thr);
System.out.println();
}
This works for almost everything, except when the numbers entered are all
descending. Example: If you enter 5,4,3,2,1 you get 5,4,3 as answers when
you should get 1,2,3.
If you enter 2,18,5,3,1,0,9,100 however you get the correct answer of 8,2,7
Any ideas?
No comments:
Post a Comment