技术求助:完善Java程序以输出马拉松冠亚军的姓名及成绩
Fixing Your Marathon Top 2 Finisher Code
No worries, let's get that second place logic sorted out! Your current code does a solid job tracking the fastest runner, but we just need to add variables to keep tabs on the second-fastest too. Here's how to adjust it step by step:
First, let's spot the small issues in your existing code:
- You initialized
firsttotimeInMinutes[1]which could miss a faster runner at index 0 right off the bat. - You didn't have dedicated variables to track the second place's time and corresponding runner index.
Here's the revised code with clear comments explaining each part:
public class MitAssignment3Chapter7 { public static void main(String args[]) { String runners[] = {"Gene", "Elvis", "Presley", "Felicity", "Welcome"}; int[] timeInMinutes = {40, 50, 76, 56, 62}; // Initialize indices and times for first and second place int firstIndex = 0; int secondIndex = 1; int firstTime = timeInMinutes[0]; int secondTime = timeInMinutes[1]; // Fix initial ordering in case the first runner is slower than the second if (firstTime > secondTime) { // Swap indices int tempIndex = firstIndex; firstIndex = secondIndex; secondIndex = tempIndex; // Swap times int tempTime = firstTime; firstTime = secondTime; secondTime = tempTime; } // Loop through the rest of the runners (starting from index 2) for (int a = 2; a < timeInMinutes.length; a++) { int currentTime = timeInMinutes[a]; if (currentTime < firstTime) { // Current runner is faster than first place: demote first to second, set current as new first secondTime = firstTime; secondIndex = firstIndex; firstTime = currentTime; firstIndex = a; } else if (currentTime < secondTime) { // Current runner is faster than second but slower than first: update second place secondTime = currentTime; secondIndex = a; } // Do nothing if current time is slower than both first and second } // Print out the final results System.out.println("The winner of the marathon is: " + runners[firstIndex] + " with " + firstTime + " minutes"); System.out.println("The second place is: " + runners[secondIndex] + " with " + secondTime + " minutes"); } }
How this logic works:
- Initial Setup: We start by setting the first two runners as initial first/second, then swap them if needed to ensure
firstTimeis always the faster (smaller) value. - Loop Through Runners:
- If the current runner’s time beats the first place, we move the original first place to second, then set the current runner as the new first.
- If the current runner is faster than second place but slower than first, we just update the second place variables.
- Output: Finally, we print both the first and second place results clearly.
Testing this with your sample data will output:
The winner of the marathon is: Gene with 40 minutes The second place is: Elvis with 50 minutes
内容的提问来源于stack exchange,提问作者user9816925
相关产品推荐
相关产品推荐

