JAVA-在包含不同信息的TXT文件中进行扫描很困难



我有一个文本文件,其中包含一个名称列表和一个图书列表,格式如下:

5
Prisoner Azkaban
J. k. Rowling
Eragon
Christopher Paolini
Ulysses
James Joyce
Of mice and men
John Steinbeck
War and peace
Leo Tolstoy
4
Craig David
Isabel Campbell
Lee Rinaldo
Bethany Waters

数字告诉你有多少";对象";在数字之后,以书名>author,则此模式在列出用户名的users部分停止重复。

这是我对代码的尝试:

Scanner inFile = new Scanner(new FileReader("C:\Users\finla\IdeaProjects\Untitled1\src\books2.txt"));

int numberOfBooks = inFile.nextInt();

for (int i= 0; i <= numberOfBooks; i++){
String bookName =  inFile.nextLine();
System.out.println("Book name: " + bookName);
String bookAuthor = inFile.nextLine();
System.out.println("Book author: " + bookAuthor);
}
int numberOfUsers = inFile.nextInt();
for (int i= 0; i <= numberOfUsers; i++){
String userName =  inFile.nextLine();
System.out.println("User name: " + userName);
}

这是输出:

Book name: 
Book author: Prisoner Azkaban
Book name: J. k. Rowling
Book author: Eragon
Book name: Christopher Paolini
Book author: Ulysses
Book name: James Joyce
Book author: Of mice and men
Book name: John Steinbeck
Book author: War and peace
Book name: Leo Tolstoy
Book author: 4

这本书的作者把我贴错地方了。循环不应该在末尾打印出4。我希望能够在最后阅读人员名单。关于为什么我的代码不起作用,你有什么建议吗?我尝试过使用next((而不是nextline((,但这并不能解决问题,只从每行中获取第一个字符串。

您希望for循环从0到<计数或从1到计数,如

for (int i= 0; i < numberOfBooks; i++){
}

你有<=,这意味着你消耗了1行太多。

开始处的空行:

当使用inFile.nextInt();时,它只获取int,而不使用n行末尾的换行符。

有几种方法可以解决这个问题,其中一种选择是使用整行并将其解析为int,例如:

int numberOfBooks = Integer.parseInt(inFile.nextLine());

否则,您只需在使用nextInt后使用一个空白的nextLine调用即可用完线路的其余部分:

int numberOfBooks = inFile.nextInt();
inFile.nextLine();

末尾的额外行:

由于<=,您的循环运行了额外的时间,请记住循环从0开始,因此正确的方法是只使用<:

for (int i= 0; i < numberOfBooks; i++){
...
}

最新更新