Java数组添加元素问题:计数器作为索引失效求助
Hey there! Let's break down what's going wrong with your code and fix it step by step. I see you're stuck on the addDonor method and the counter logic—let's start with the biggest issue first.
1. The Counter is Resetting Every Time You Call addDonor
Right now, your counter is a local variable inside addDonor, which means every time you call the method, it gets set back to 0. That's why every new donor you add overwrites the first position in your arrays instead of moving to the next one.
Fix: Pass the counter as a parameter to addDonor, and return the updated counter value so you can track it in the main method. This way, we always know the next empty slot in the arrays.
2. Mobile Number Validation Logic is Reversed
Your current check for invalid mobile numbers is backwards. Let's assume you want valid numbers to be 10 digits long and start with "0"—your original code enters the loop when the number is too short AND doesn't start with 0, then breaks when it's too long OR starts with 0. That's not the behavior you want.
Fix: Rewrite the validation to loop until the user enters a number that meets the valid criteria.
3. Blood Group Validation Loop is Always True
The condition while (blood != 'a' || blood != 'b' || blood != 'c') will never be false—no matter what blood type the user enters, it can't be equal to all three at once. Plus, you're checking for 'c' but your prompt specifies A/B/O.
Fix: Check if the blood type is NOT one of the valid options (A/B/O, case-insensitive), and loop until it is. Also, normalize the input to uppercase so you store consistent values.
4. Duplicate readAndVerify Calls in Main
You're calling readAndVerify() twice before getting the user's choice—this means the user has to enter their selection twice, which is confusing.
Fix: Call it once and store the result in the choice variable.
5. Exit Logic & Printing All Donor Info
Right now, your exit check only looks for lowercase "e", and you're only printing the first two names instead of all donors.
Fix: Handle both uppercase "E" and lowercase "e" in your switch, then loop through all arrays to print every donor that was added.
Corrected Full Code
Here's the fixed version of your code with all these changes:
import java.util.Scanner; public class DonorManager { // Display main menu (added for completeness since you referenced it) public static void displayMainMenu() { System.out.println("\n=== Main Menu ==="); System.out.println("1. Create Donor Account"); System.out.println("E. Exit and Print All Accounts"); System.out.print("Enter your choice: "); } // Read and verify user input (assumed implementation) public static String readAndVerify() { Scanner input = new Scanner(System.in); return input.nextLine().trim(); } public static int addDonor(String[] names, String[] mobiles, char[] bloodGroups, int[] donationCounts, int[] bloodStocks, int counter) { Scanner input = new Scanner(System.in); System.out.print("Enter the name (first and last): "); String name = input.nextLine(); // Mobile number validation String phone = ""; boolean validMobile = false; while (!validMobile) { System.out.print("Enter Mobile No.: "); phone = input.next().trim(); // Valid mobile: 10 digits, starts with 0 if (phone.length() == 10 && phone.startsWith("0")) { validMobile = true; } else { System.out.println("Wrong Mobile NO... try again! (Must be 10 digits starting with 0)"); } } input.nextLine(); // Consume leftover newline // Blood group validation char blood = ' '; boolean validBlood = false; while (!validBlood) { System.out.print("Enter Blood Group Type (A, B or O): "); String bloodInput = input.nextLine().trim().toUpperCase(); if (bloodInput.length() == 1 && (bloodInput.charAt(0) == 'A' || bloodInput.charAt(0) == 'B' || bloodInput.charAt(0) == 'O')) { blood = bloodInput.charAt(0); validBlood = true; } else { System.out.println("Wrong Blood Group Type... try again! (Enter A, B, or O)"); } } // Store donor info at current counter position names[counter] = name; mobiles[counter] = phone; bloodGroups[counter] = blood; donationCounts[counter] = 1; bloodStocks[counter] = 1; // Return incremented counter for next donor return counter + 1; } public static void main(String[] args) { final int MAX_DONORS = 20; String[] names = new String[MAX_DONORS]; String[] mobiles = new String[MAX_DONORS]; char[] bloodGroups = new char[MAX_DONORS]; int[] donationCounts = new int[MAX_DONORS]; int[] bloodStocks = new int[MAX_DONORS]; int donorCounter = 0; // Tracks next empty array index while (true) { displayMainMenu(); String choice = readAndVerify(); switch (choice.toUpperCase()) { case "1": if (donorCounter < MAX_DONORS) { donorCounter = addDonor(names, mobiles, bloodGroups, donationCounts, bloodStocks, donorCounter); } else { System.out.println("Maximum number of donors reached!"); } break; case "E": // Print all donor accounts System.out.println("\n=== All Donor Accounts ==="); for (int i = 0; i < donorCounter; i++) { System.out.println("\nDonor " + (i+1) + ":"); System.out.println("Name: " + names[i]); System.out.println("Mobile: " + mobiles[i]); System.out.println("Blood Group: " + bloodGroups[i]); System.out.println("Donation Count: " + donationCounts[i]); System.out.println("Blood Stock: " + bloodStocks[i]); } System.out.println("\nExiting program..."); return; // Exit main method to end program default: System.out.println("Invalid choice! Please enter 1 or E."); } } } }
Key Changes Recap:
- Donor Counter: Now passed to
addDonorand returned incremented, so we never overwrite existing entries. - Mobile Validation: Clear loop that runs until the user enters a valid 10-digit number starting with 0.
- Blood Group Validation: Converts input to uppercase for consistency, and checks against valid options correctly.
- Main Flow: Only calls
readAndVerifyonce per menu iteration, handles both "e" and "E", and prints all donors on exit. - Array Bound Check: Prevents adding more donors than the array can hold.
This should fix your counter issue and make the program work exactly as you intended!
内容的提问来源于stack exchange,提问作者Mr. java

