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

Java中从用户输入填充String数组时首索引无法赋值的问题

问题分析与解决方案

嗨,刚帮你排查了代码里的问题,核心原因是输入缓冲区残留的换行符在搞鬼!

问题根源

当你用sc.nextInt()读取书籍数量时,它只会读取数字部分,但你输入完数字按下的回车键(也就是换行符\n)会留在输入缓冲区里。接下来调用addBook()方法时,第一个sc.nextLine()会直接读取这个残留的换行符,导致数组第一个位置被空字符串填充,而不是你输入的书名。

修复方案

这里给你两种简单的解决办法:

方法1:消费残留的换行符

在sc.nextInt()之后,额外调用一次sc.nextLine()来吃掉缓冲区里的换行符:

Library(){
    System.out.print("Enter the number of books you want to add to the library: ");
    numOfBooks = sc.nextInt();
    sc.nextLine(); // 新增这行,处理残留的换行符
    this.addBook = new String[numOfBooks];
}

方法2:全程使用nextLine()读取输入

把读取书籍数量的逻辑改成用nextLine()读取,再转换成整数,这样就不会有残留的换行符问题:

Library(){
    System.out.print("Enter the number of books you want to add to the library: ");
    String numInput = sc.nextLine();
    numOfBooks = Integer.parseInt(numInput);
    this.addBook = new String[numOfBooks];
}

额外代码优化建议

你的方法名addBook和数组变量名addBook重名了,虽然Java语法允许,但会降低代码可读性。建议把数组变量改成更清晰的名字,比如books,修改后代码更易维护:

class Library{
    Scanner sc = new Scanner(System.in);
    int numOfBooks;
    String[] books; // 重命名数组变量

    Library(){
        System.out.print("Enter the number of books you want to add to the library: ");
        numOfBooks = sc.nextInt();
        sc.nextLine();
        this.books = new String[numOfBooks];
    }

    public String[] addBook(){
        for(int i=0; i<numOfBooks; i++){
            int j = i+1;
            System.out.print("Add Book "+j+" Name: ");
            this.books[i] = sc.nextLine();
        }
        return books;
    }

    public void showAvailableBooks(){
        for(int i=0; i<numOfBooks; i++){
            System.out.println(books[i]);
        }
    }
}

修复后的完整代码

package com.company;
import java.util.Scanner;
class Library{
    Scanner sc = new Scanner(System.in);
    int numOfBooks;
    String[] books;

    Library(){
        System.out.print("Enter the number of books you want to add to the library: ");
        numOfBooks = sc.nextInt();
        sc.nextLine(); // 处理换行符
        this.books = new String[numOfBooks];
    }

    public String[] addBook(){
        for(int i=0; i<numOfBooks; i++){
            int j = i+1;
            System.out.print("Add Book "+j+" Name: ");
            this.books[i] = sc.nextLine();
        }
        return books;
    }

    public void showAvailableBooks(){
        for(int i=0; i<numOfBooks; i++){
            System.out.println(books[i]);
        }
    }
}
public class CWH_51_Exercise_4 {
    public static void main(String[] args) {
        Library l = new Library();
        l.addBook();
        l.showAvailableBooks();
    }
}

内容的提问来源于stack exchange,提问作者Shantanu Study Circle

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:20:20