You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java实验问题排查:输出不符及循环输入报错求助

Fixing Your Java Student Score Tracker Input Issue

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 use scanner.nextLine() to consume the leftover newline—this ensures the next nextLine() 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

  1. Run the program.
  2. Enter a student name, then their score (repeat as needed).
  3. Type alldone when you're finished—you'll see the student with the highest score printed immediately.

内容的提问来源于stack exchange,提问作者MGA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:53:08