レースの上位 5 位を表示するプログラムを作成しようとしています。コードはコンパイルされますが、実行すると明らかな論理エラーが発生します。5 か所すべてで同じファイナリストが繰り返されるため、1 位が 1 位、2 位、3 位…と続きます。
これが私のコードです:
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.