如何解决Java学生成绩统计程序的无限循环问题?
Fixing the Infinite Loop in Your Java Student Grade Tally Program
Hey there! Let’s tackle that infinite loop issue you’re facing with your student grade program. Nested input loops can be tricky, especially when dealing with different sentinel values (-1 for individual students, "END" for the whole program) and mixed input types (strings and integers). Let’s break down the common pitfalls and fix this step by step.
Common Causes of the Infinite Loop
First, let’s identify why your loop might be stuck:
- Mixing up sentinel values: If your outer loop doesn’t check for "END" before reading a student’s name, it might treat "END" as a student’s first name, then try to read integers for scores—leading to input mismatches or endless attempts to read invalid data.
- Unchecked input type mismatches: Using
nextInt()when the next input is a string (like "END") will throw anInputMismatchException, and if unhandled, the Scanner can get stuck in a broken state that causes infinite looping. - Incorrect inner loop exit logic: If your inner loop doesn’t properly skip the
-1sentinel or fails to hand control back to the outer loop, you might end up reprocessing the same input over and over.
Step-by-Step Fix & Example Code
Here’s a corrected version of your program with explanations for key fixes:
import java.util.Scanner; public class StudentGradeCalculator { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Outer loop: Process each student until "END" is encountered while (scanner.hasNext()) { String nextToken = scanner.next(); // First check if we've reached the program end sentinel if (nextToken.equals("END")) { break; } // If not END, it's the student's first name String firstName = nextToken; String lastName = scanner.next(); int totalScore = 0; // Inner loop: Read scores until -1 is found while (scanner.hasNextInt()) { int score = scanner.nextInt(); // Exit inner loop when we hit the student sentinel if (score == -1) { break; } // Validate score (skip invalid negative scores) if (score < 0) { System.out.printf("Warning: Invalid score %d for %s %s. Skipping.%n", score, firstName, lastName); continue; } totalScore += score; } // Print the student's total System.out.printf("%s %s's total score: %d%n", firstName, lastName, totalScore); // Clean up any non-integer input left after inner loop (prevents stuck state) if (scanner.hasNext() && !scanner.hasNextInt()) { scanner.next(); } } scanner.close(); } }
Key Fixes Explained
- Check for "END" first: The outer loop reads the next token immediately and checks if it’s "END" before processing a student. This prevents "END" from being misinterpreted as a student name.
- Safe integer reading: The inner loop uses
hasNextInt()to confirm the next input is an integer before callingnextInt(), avoiding input mismatch exceptions that can break the Scanner. - Input validation: Added a check to skip invalid negative scores (excluding
-1), fulfilling the "validate user input" requirement. - Clean up invalid input: After the inner loop, we skip any remaining non-integer input to ensure the outer loop can correctly read the next student’s name (or "END").
Troubleshooting Tips
If you still run into issues, try these debugging steps:
- Add debug prints: Insert
System.out.println("Reading: " + nextToken);or similar inside loops to see exactly what input the program is processing. This will quickly reveal if it’s stuck on a bad input value. - Handle exceptions: Wrap input reading in a
try-catchblock forInputMismatchExceptionto catch invalid inputs and reset the Scanner state withscanner.next(). - Test edge cases: Try input like
ENDimmediately, a student with no scores (just-1), or invalid non-numeric scores to ensure your loop handles them gracefully.
内容的提问来源于stack exchange,提问作者Megan V
相关产品推荐
相关产品推荐

