我正在嘗試創建一個程序,提供比賽中前5名的地方。代碼編譯,但是當你運行它時,有一個明顯的邏輯錯誤。它重複在所有5位相同的決賽,所以第一名被放置在第一,第二,第三,等等...嵌套if語句的邏輯錯誤
這裏是我的代碼:
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.
我應該發起變量數組中不同的元素?我知道,爲了使代碼與變量一起編譯,它必須被初始化爲某個值。 –
將每個變量初始化爲'Double.MAX_VALUE',你應該很好去。我會用特定的代碼更新我的帖子。 –
謝謝!代碼現在正在工作。 –