Java程序无法识别文本文件中除首个名称外的其他名称求助
Hey there! Let's break down why your code only works for Sally and get it sorted to handle all the names in your file correctly. I’ve gone through your code and sample data, and here’s what’s going wrong, plus a fixed version of your code:
Key Issues in Your Current Code
1. Name Prefix Mismatch
Your file uses names prefixed with a - (like -Sally, -Sam), but your nameSearch() method asks users to enter names without that hyphen. When your code checks nameCheck.equals(name), -Sally will never match Sally—the only reason Sally worked was a fluke in your messy loop logic!
2. Tangled Scanner Loop Logic
Your dataScan method has a broken flow that eats up file tokens incorrectly:
- You start by reading
nameCheck = file.next(), but immediately callfile.next()again in thewhilecondition, which skips the next token entirely. - The nested
while(file.hasNext())loop creates an infinite loop risk or drains the file too early. - The
else { file.nextLine(); }line is a killer: your entire file is one line, so this skips all remaining content as soon as it hits a non-matching name, which is why Sam/Samantha/Samir never get processed.
3. Vague Exception Handling
Catching all Exception types and printing a generic message hides real issues (like format errors) instead of giving useful feedback.
Fixed Code
import java.util.*; import java.io.*; public class TestSpace1 { public static void main(String[] args) throws FileNotFoundException { Scanner fileInput = new Scanner(new File("names.txt")); String nameUsed = nameSearch(); // Add the hyphen prefix to match the file's format String targetName = "-" + nameUsed; dataScan(fileInput, targetName); fileInput.close(); // Clean up file resource } public static void dataScan(Scanner file, String targetName) { boolean nameFound = false; while (file.hasNext()) { String currentToken = file.next(); // Check if we've hit the target name if (currentToken.equals(targetName)) { nameFound = true; int year = 1910; // Read and print the 11 ranking values for (int i = 0; i < 11; i++) { if (file.hasNextInt()) { int ranking = file.nextInt(); System.out.println(year + ": " + ranking); year += 10; } } break; // Exit loop once we've processed the target name } else { // Skip the 11 ranking values for non-target names for (int i = 0; i < 11; i++) { if (file.hasNext()) { file.next(); } } } } if (!nameFound) { System.out.println("Sorry, that name wasn't found in the data."); } } public static String nameSearch() { Scanner input = new Scanner(System.in); System.out.println("This program allows you to search through the"); System.out.println("data from the Social Security Administration"); System.out.println("to see how popular a particular name has been"); System.out.println("since 1900."); System.out.print("What name would you like to search? "); String name = input.nextLine().trim(); // Trim any accidental spaces input.close(); // Clean up input resource return name; } }
What Changed & Why
- Hyphen Auto-Add: We prepend a
-to the user’s input so it matches the file’s name format—no need for users to remember to type the hyphen. - Simplified Scan Logic: We loop through the file one token at a time. When we hit a name, we either process its 11 rankings (if it’s the target) or skip those rankings to move to the next name.
- Resource Cleanup: Added
close()calls for both Scanners to avoid resource leaks. - Clear Feedback: If the name isn’t found, we print a specific message instead of a generic exception catch-all.
- Safety Checks: Added
file.hasNextInt()andfile.hasNext()checks to avoid crashes if the file format is off.
内容的提问来源于stack exchange,提问作者dat_cube

