Java球员数据程序求助:选项2无法排序及显示内容
Hey there! Let's dig into why your menu option 2 isn't working as expected—there are a couple of key bugs in your code and some input handling quirks that are throwing things off. Here's the breakdown and fix:
First, the Critical Bugs Causing Option 2 to Fail
Array Index Out-of-Bounds in Sorting
In yourinputSort()method, the inner loop usesi < 10, but your arrays only hold 3 elements (you defined them asnew String[3], etc.). This causes the code to access non-existent array indices, breaking the sorting logic entirely and potentially hiding valid data. You need to use the actual array length instead of hardcoding 10.Only Sorting the Age Array (Data Desync)
Your selection sort only swaps elements in theagearray, but doesn't update the correspondingname,position, oraveragearrays. This means after sorting, a player's age won't match their name/position/average anymore—so even if the sort worked, your filtered results would be wrong.Mixed Input Handling Causing Corrupted Data
Using bothBufferedReaderandScannerininputInfo()leads to leftover newline characters in the input buffer. For example, after usingp.nextInt()to read an age, the nextin.readLine()will read an empty string for the position, corrupting your stored data.
Fixed Code with Corrected Logic
Here's your code with all the above issues fixed, plus some quality-of-life improvements:
import java.util.Scanner; public class BlueJays { // Use a constant for player count to make future changes easier private static final int PLAYER_COUNT = 3; static String name[] = new String[PLAYER_COUNT]; static int age[] = new int[PLAYER_COUNT]; static String position[] = new String[PLAYER_COUNT]; static double average[] = new double[PLAYER_COUNT]; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int menuChoice = 1; System.out.println("Hello and Welcome to Blue Jay Java Sort"); while (menuChoice != 3) { System.out.println("\nEnter Menu Choice"); System.out.println("**********************"); System.out.println("(1) => Enter Blue Jay Data "); System.out.println("(2) => Display Possible Draft Choices "); System.out.println("(3) => Exit "); // Validate menu input to avoid invalid entries while (!scanner.hasNextInt()) { System.out.println("Please enter a valid number (1-3)"); scanner.next(); // Clear invalid input } menuChoice = scanner.nextInt(); switch (menuChoice) { case 1: inputInfo(scanner); break; case 2: inputSort(); displayFilteredPlayers(); break; case 3: System.out.println("Exiting program..."); return; default: System.out.println("Invalid option—please pick 1, 2, or 3"); } } scanner.close(); } // Use a single Scanner for all input to avoid buffer issues public static void inputInfo(Scanner scanner) { for (int x = 0; x < PLAYER_COUNT; x++) { System.out.println("\n===== Enter Player " + (x + 1) + " Details ====="); // Clear leftover newline before reading name if (x > 0) { scanner.nextLine(); } System.out.print("Full Name: "); name[x] = scanner.nextLine(); // Validate age input System.out.print("Age: "); while (!scanner.hasNextInt()) { System.out.println("Please enter a valid integer for age"); scanner.next(); } age[x] = scanner.nextInt(); // Clear newline before reading position scanner.nextLine(); System.out.print("Position: "); position[x] = scanner.nextLine(); // Validate batting average input System.out.print("Batting Average: "); while (!scanner.hasNextDouble()) { System.out.println("Please enter a valid number (e.g., 0.280)"); scanner.next(); } average[x] = scanner.nextDouble(); } } // Sort all arrays in sync to keep player data matched public static void inputSort() { for (int x = 0; x < PLAYER_COUNT - 1; x++) { int smallestIndex = x; // Use array length instead of hardcoding 3 for (int i = x + 1; i < PLAYER_COUNT; i++) { if (age[i] < age[smallestIndex]) { smallestIndex = i; } } // Swap age int tempAge = age[x]; age[x] = age[smallestIndex]; age[smallestIndex] = tempAge; // Swap name String tempName = name[x]; name[x] = name[smallestIndex]; name[smallestIndex] = tempName; // Swap position String tempPosition = position[x]; position[x] = position[smallestIndex]; position[smallestIndex] = tempPosition; // Swap batting average double tempAverage = average[x]; average[x] = average[smallestIndex]; average[smallestIndex] = tempAverage; } } // Separate display logic for clarity public static void displayFilteredPlayers() { System.out.println("\n===== Eligible Draft Choices ====="); System.out.printf("%-20s %-5s %-15s %-15s\n", "Name", "Age", "Position", "Batting Average"); System.out.println("-----------------------------------------------------------"); boolean hasEligiblePlayers = false; for (int x = 0; x < PLAYER_COUNT; x++) { // Match your requirement: under 25 AND batting average ≥ 0.280 if (age[x] < 25 && average[x] >= 0.280) { System.out.printf("%-20s %-5d %-15s %-15.3f\n", name[x], age[x], position[x], average[x]); hasEligiblePlayers = true; } } if (!hasEligiblePlayers) { System.out.println("No players meet the eligibility criteria"); } } }
Further Optimization Suggestions
Use Object-Oriented Design: Instead of parallel arrays, create a
Playerclass to encapsulate all player attributes. This eliminates the need to sync multiple arrays during sorting and makes the code easier to maintain. Example:class Player { private String name; private int age; private String position; private double battingAverage; public Player(String name, int age, String position, double battingAverage) { this.name = name; this.age = age; this.position = position; this.battingAverage = battingAverage; } // Getters for sorting/filtering public int getAge() { return age; } public double getBattingAverage() { return battingAverage; } @Override public String toString() { return String.format("%-20s %-5d %-15s %-15.3f", name, age, position, battingAverage); } }You can then use an
ArrayList<Player>to store players, and sort withCollections.sort(players, Comparator.comparingInt(Player::getAge))for cleaner code.Add More Input Validation: Ensure batting averages are between 0 and 1, and ages are reasonable (e.g., 16-40) to prevent nonsensical data.
Improve User Feedback: Add confirmation messages after saving player data, and clearer prompts for each input field.
内容的提问来源于stack exchange,提问作者Mina

