在JAVA中接受用户输入以填充字符串数组时出现问题-无法填充数组的第一个索引位置



//问题声明:WAP创建类库,并使用addBook和showAvailableBooks方法存储和显示库中的书籍。//我是java的新手,在运行以下程序后遇到了一个问题。我无法填充数组addBook的第一个索引位置。

package com.company;
import java.util.Scanner;
class Library{
Scanner sc = new Scanner(System.in);
int numOfBooks;
String[] addBook;
Library(){
System.out.print("Enter the number of books you want to add to the library: ");
numOfBooks = sc.nextInt();
this.addBook = new String[numOfBooks]; //New String called "addBook" is being created.
}
public String[]addBook(){
for(int i=0; i<numOfBooks; i++){
int j = i+1;
System.out.print("Add Book "+j+" Name: ");
this.addBook[i] = sc.nextLine();
}
return addBook;
}
public void showAvailableBooks(){
for(int i=0; i<numOfBooks; i++){
System.out.println(addBook[i]);
}
}
}
public class CWH_51_Exercise_4 {
public static void main(String[] args) {
Library l = new Library();
l.addBook();
l.showAvailableBooks();

}
}

这可能是由库构造函数中的sc.nextInt((引起的。它读取给定的int,但不读取'\n'字符(按enter键时为原始字符(。

当第一次调用nextLine((时,它读取缺少的'\n'。

请尝试在每次nextInt((之后调用nextLine((。

System.out.print("Enter the number of books you want to add to the library: ");
numOfBooks = sc.nextInt();
sc.nextLine(); // Consume 'n'
this.addBook = new String[numOfBooks];

我建议您避免使用sc.nextInt(),而是使用以下内容:

numOfBooks = Integer.parseInt(sc.nextLine());

有关的解释,请参阅此问题

最新更新