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

Java Scanner输入异常问题排查:LineLimitException提前触发及输入流程错乱解决

Hey JenPann, let's break down what's causing that weird input behavior and fix it up properly!

The Root Cause: Unconsumed Newline in Scanner Buffer

When you use input.nextInt() to read the number of employees, it only captures the numeric value—but the newline character (\n) you entered after typing the number stays stuck in the Scanner's input buffer. The very next input.nextLine() call reads this empty newline instead of waiting for you to type a name, resulting in an empty name string. That's why you see the error message immediately after entering the employee count, without ever typing a name. On top of that, your current logic doesn't properly loop to re-request a valid name, so it jumps straight to the wage prompt.

Step-by-Step Fixes

1. Clear the Newline After nextInt()

First, add an extra input.nextLine() right after reading numEmployees to consume that leftover newline:

int numEmployees = input.nextInt();
input.nextLine(); // Eat the leftover newline character

2. Properly Loop for Valid Name Input (With Custom Exception)

Your current code just prints an error but doesn't actually wait for a new input, and it doesn't throw your custom LineLimitException as intended. Let's wrap the name input in a loop that keeps asking until a valid name is entered, and throws/catches your custom exception correctly:

for (int count = 1; count <= numEmployees; count++) {
    String name = null;
    while (true) {
        System.out.println("Enter employee " + count + "'s name");
        name = input.nextLine();
        try {
            // Add trim() to catch inputs that are just whitespace
            if (name.trim().length() < 1) {
                throw new LineLimitException("Name must be greater than one character. Please try again.");
            }
            break; // Exit loop once valid name is entered
        } catch (LineLimitException e) {
            System.out.println(e.getMessage());
        }
    }
    // Rest of your wage/hours input logic goes here...
}

3. Fix Other Hidden Issues

  • Wrong Timing for printSalaryReport: You're calling this method inside the loop, which rewrites the entire CSV file every time you add an employee. Move it outside the loop so it runs once after all employees are added. Also, you don't need to pass wage and hrsWkd as parameters—you can get those values directly from the Employee objects in the list:
    // Update the method signature
    private static void printSalaryReport(ArrayList<Employee> person) {
        // Keep the existing logic inside—you already pull data from each Employee object
    }
    
    // Call it after the for loop ends
    printSalaryReport(person);
    
  • Empty Catch Block: Your catch (IOException err){} swallows errors silently, which makes debugging impossible. Add a print statement to log exceptions:
    catch (IOException err){
        err.printStackTrace(); // Shows exactly what went wrong with the file write
    }
    
  • Clear Newlines After nextDouble(): Just like with nextInt(), nextDouble() leaves a newline in the buffer. Add input.nextLine() after reading wage and hours to avoid issues if you add more input later:
    System.out.println("Enter employee's hourly wage");
    double wage = input.nextDouble();
    input.nextLine(); // Clear newline
    
    System.out.println("Enter how many hours worked");
    double hrsWkd = input.nextDouble();
    input.nextLine(); // Clear newline
    
Full Fixed Core Code Snippet

Here's what your updated main method will look like:

public static void main(String[] args) {
    ArrayList<Employee> person = new ArrayList<Employee>();
    Scanner input = new Scanner(System.in);
    System.out.println("How many employees are there?");
    int numEmployees = input.nextInt();
    input.nextLine(); // Clean up newline after nextInt()

    for (int count = 1; count <= numEmployees; count++) {
        String name = null;
        while (true) {
            System.out.println("Enter employee " + count + "'s name");
            name = input.nextLine();
            try {
                if (name.trim().length() < 1) {
                    throw new LineLimitException("Name must be greater than one character. Please try again.");
                }
                break;
            } catch (LineLimitException e) {
                System.out.println(e.getMessage());
            }
        }

        System.out.println("Enter employee's hourly wage");
        double wage = input.nextDouble();
        input.nextLine(); // Clean up newline

        System.out.println("Enter how many hours worked");
        double hrsWkd = input.nextDouble();
        input.nextLine(); // Clean up newline

        person.add(new Employee(name, wage, hrsWkd));
    }

    printSalaryReport(person);
    input.close();
    System.out.println("CSV File Created.");
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 10:07:29