Java实验问题排查:输出不符及循环输入报错求助
Hey there! Let's figure out why your program acts up when entering the second student's name—this is a super common gotcha with Java's Scanner class. Here's what's going wrong and how to fix it:
The Root Cause
When you use nextInt() to read a student's score, it only grabs the numeric value and leaves the newline character (from pressing Enter) in the input buffer. The next time you call nextLine() to read a name, it picks up that leftover newline as an empty string instead of waiting for your input—this is what's causing the unexpected error or behavior.
Corrected Full Code
Here's a revised version of your program that fixes the input handling, adds validation, and meets all your requirements:
import java.util.Scanner; public class StudentScoreTracker { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String topStudent = ""; int highestScore = -1; // Initialize to a value lower than any valid score while (true) { // Prompt for student name System.out.print("Enter student name (type 'alldone' to finish): "); String studentName = scanner.nextLine(); // Exit loop if user enters "alldone" (case-insensitive) if (studentName.equalsIgnoreCase("alldone")) { break; } // Prompt for and validate score input System.out.print("Enter " + studentName + "'s score: "); while (!scanner.hasNextInt()) { System.out.println("Oops, that's not a valid number! Please enter an integer score:"); scanner.nextLine(); // Clear the invalid input from the buffer } int studentScore = scanner.nextInt(); scanner.nextLine(); // Consume the leftover newline after nextInt() // Update highest score and top student if (studentScore > highestScore) { highestScore = studentScore; topStudent = studentName; } } // Display results if (!topStudent.isEmpty()) { System.out.printf("The student with the highest score is: %s (Score: %d)%n", topStudent, highestScore); } else { System.out.println("No student data was entered."); } scanner.close(); } }
Key Fixes & Improvements
- Clearing the input buffer: After calling
nextInt(), we usescanner.nextLine()to consume the leftover newline—this ensures the nextnextLine()call reads your actual input, not an empty string. - Input validation: Added a loop to check if the score is a valid integer, preventing the program from crashing if someone enters non-numeric text.
- Case-insensitive exit: The loop breaks if you enter "alldone", "ALLDONE", or any variation, making the program more user-friendly.
- Edge case handling: Checks if no students were entered, so it doesn't output an empty student name.
How to Test
- Run the program.
- Enter a student name, then their score (repeat as needed).
- Type
alldonewhen you're finished—you'll see the student with the highest score printed immediately.
内容的提问来源于stack exchange,提问作者MGA

