到目前为止我有这个:
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();
}
这几乎适用于所有情况,除非输入的数字都是降序的。示例:如果您输入 5,4,3,2,1,您会得到 5,4,3 作为答案,而您应该得到 1,2,3。
如果你输入 2,18,5,3,1,0,9,100 但是你得到的正确答案是 8,2,7
有任何想法吗?