Java技术问题:数组元素长度校验与全名输入逻辑实现
Hey there! Let's break down your two Java questions with practical, easy-to-follow solutions.
There are a couple of straightforward ways to handle this, depending on your performance needs and code style.
方法1:用HashSet高效检测(推荐)
This method uses a HashSet to track the lengths of elements as we iterate through the array. Since HashSet doesn't allow duplicates, if we try to add a length that's already present, we know we've found our match. It runs in O(n) time, which is great for larger arrays.
import java.util.HashSet; import java.util.Set; public class DuplicateLengthChecker { public static boolean hasDuplicateLength(String[] arr) { Set<Integer> lengthTracker = new HashSet<>(); for (String element : arr) { int len = element.length(); // add() returns false if the length is already in the set if (!lengthTracker.add(len)) { return true; } } return false; } }
方法2:双重循环暴力比较
If you don't want to use a collection (maybe for super small arrays), you can compare each element's length with every other element. Just note this runs in O(n²) time, so it's not ideal for big datasets.
public class DuplicateLengthChecker { public static boolean hasDuplicateLength(String[] arr) { for (int i = 0; i < arr.length; i++) { int currentLen = arr[i].length(); for (int j = i + 1; j < arr.length; j++) { if (currentLen == arr[j].length()) { return true; } } } return false; } }
Let's build out this feature with all your requirements in mind—input handling, validation rules, and storing the split name arrays. Here's a complete, commented implementation:
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class FullNameManager { public static void main(String[] args) { Scanner inputScanner = new Scanner(System.in); List<String[]> validNamesList = new ArrayList<>(); // Stores split arrays of valid full names System.out.println("Enter full names (type 'fim' to stop):"); while (true) { // Stop if we hit the 10 valid names limit if (validNamesList.size() >= 10) { System.out.println("Maximum 10 valid names reached. Stopping input."); break; } String userInput = inputScanner.nextLine().trim(); // Handle termination with "fim"—make sure we have at least 5 valid names first if ("fim".equalsIgnoreCase(userInput)) { if (validNamesList.size() < 5) { System.out.println("You need at least 5 valid names. Please keep entering."); continue; } break; } // Rule 1: Full name length can't exceed 120 characters if (userInput.length() > 120) { System.out.println("Nome Inválido"); continue; } // Split full name into parts (handles multiple spaces) String[] nameParts = userInput.split("\\s+"); // Rule 2: At least two parts with length 4 int fourLetterPartCount = 0; for (String part : nameParts) { if (part.length() == 4) { fourLetterPartCount++; } } if (fourLetterPartCount >= 2) { validNamesList.add(nameParts); System.out.println("Valid name added."); } else { System.out.println("Nome Inválido"); } } // Optional: Display all valid split name arrays System.out.println("\nAll valid split name arrays:"); for (int i = 0; i < validNamesList.size(); i++) { System.out.printf("Name %d: ", i + 1); for (String part : validNamesList.get(i)) { System.out.print(part + " "); } System.out.println(); } inputScanner.close(); } }
Key details about this implementation:
- Uses
ArrayList<String[]>to store each valid full name's split parts, making it easy to access later - Handles edge cases: ensures we get at least 5 valid names before allowing "fim" to terminate, stops at 10 valid names
split("\\s+")splits the full name on any number of spaces, so it works even if the user accidentally adds extra spaces- Clearly checks both validation rules (length <=120, at least two 4-letter parts) and outputs "Nome Inválido" when either fails
内容的提问来源于stack exchange,提问作者Ruca

