我正在尝试创建一个程序来展示比赛中的前 5 名。代码可以编译,但运行时会出现明显的逻辑错误。它在所有 5 个地方重复相同的决赛选手,所以第一名被放置在第一、第二、第三,依此类推......
这是我的代码:
import java.util.Scanner;
public class Assignment0
{
public static void main (String [] args)
{
int numberOfLanes;
int lane = 0;
double first;
double second;
double third;
double fourth;
double fifth;
double [] time = null;
Scanner keyboard = new Scanner (System.in);
System.out.println ("How many lanes hold competitors?");
numberOfLanes = keyboard.nextInt();
time = new double [numberOfLanes];
for (int i = 0; i < numberOfLanes; i++)
{
System.out.println("Enter time for lane " + i);
time [i] = keyboard.nextDouble();
}
System.out.println();
System.out.println();
first = time[0];
for (int i = 0; i < time.length; i++)
{
if ( time[i] < first)
{
first = time[i];
lane = i;
}
}
System.out.println("First place = Lane " + lane + ". Time = " + first + " seconds.");
second = time[0];
for (int i = 0; i < time.length; i++)
{
if (time [i] > first)
if (time [i] < second)
{
second = time[i];
lane = i;
}
}
System.out.println("Second place = Lane " + lane + ". Time = " + second + " seconds.");
third = time[0];
for (int i = 0; i < time.length; i++)
{
if (time[i] > second)
if (time[i] < third)
{
third = time[i];
lane = i;
}
}
System.out.println("Third place = Lane " + lane + ". Time = " + third + " seconds.");
fourth = time[0];
for (int i = 0; i < time.length; i++)
{
if (time[i] > third)
if (time[i] < fourth)
{
fourth = time[i];
lane = i;
}
}
System.out.println("Fourth place = Lane " + lane + ". Time = " + fourth + " seconds.");
fifth = time[0];
for (int i = 0; i < time.length; i++)
{
if (time [i] > fourth)
if (time[i] < fifth)
{
fifth = time[i];
lane = i;
}
}
System.out.println("Fifth place = Lane " + lane + ". Time = " + fifth + " seconds.");
}
}
输出如下所示:
How many lanes hold competitors?
5
Enter time for lane 0
9.72
Enter time for lane 1
9.8
Enter time for lane 2
9.82
Enter time for lane 3
9.86
Enter time for lane 4
9.9
First place = Lane 0. Time = 9.72 seconds.
Second place = Lane 0. Time = 9.72 seconds.
Third place = Lane 0. Time = 9.72 seconds.
Fourth place = Lane 0. Time = 9.72 seconds.
Fifth place = Lane 0. Time = 9.72 seconds.