Java 扫描仪与用户输入不一致
我正在开发一个具有EditBook方法的库应用程序,但目前我在让它做我想做的事情方面遇到了问题。这是我到目前为止所拥有的 editBook()方法 下面是switch语句中的代码Java 扫描仪与用户输入不一致,java,java.util.scanner,Java,Java.util.scanner,我正在开发一个具有EditBook方法的库应用程序,但目前我在让它做我想做的事情方面遇到了问题。这是我到目前为止所拥有的 editBook()方法 下面是switch语句中的代码 case 2: //Edit a Book System.out.println("You have chosen to edit a book."); System.out.println("Enter the ID of the book you would lik
case 2: //Edit a Book
System.out.println("You have chosen to edit a book.");
System.out.println("Enter the ID of the book you would like to edit: ");
int ID = sc.nextInt();
int i = ID;
System.out.println("You are about to edit: " + mcClay.getBooks().get(i).getTitle() + " by " +
mcClay.getBooks().get(i).getAuthor() );
System.out.println("Please enter the book's new title: ");
title = sc.nextLine();
sc.next();
System.out.println("Please enter the book's new author: ");
author = sc.nextLine();
sc.next();
System.out.println("How many books do you have?: ");
while (!sc.hasNextInt()) {
System.out.println("Enter an integer!");
sc.nextLine();
}
quantity = sc.nextInt();
System.out.println("How many books currently on loan? (Enter 0 if none): ");
while (!sc.hasNextInt()) {
System.out.println("Enter an integer!");
sc.nextLine();
}
numOnLoan = sc.nextInt();
System.out.println("How many times has this book been loaned out? (Enter 0 if never): ");
while (!sc.hasNextInt()) {
System.out.println("Enter an integer!");
sc.nextLine();
}
numTimesLoaned = sc.nextInt();
我用以下输入测试了它,这就是我得到的
You have chosen to edit a book.
Enter the ID of the book you would like to edit:
1
You are about to edit: Harry Potter and the Chamber of Secrets by J.K. Rowling
Please enter the book's new title:
Harry Potter
Please enter the book's new author:
J.K Rowling
How many books do you have?:
Enter an integer!
1
How many books currently on loan? (Enter 0 if none):
0
How many times has this book been loaned out? (Enter 0 if never):
0
The new details of this book are: ID: 0Title: Author: Potter Quantity: 1 No. on Loan: 0 No. of times loaned: 0
这显然是错误的,因为没有存储正确的ID、标题或作者,即使我没有输入任何内容,“数量”的输入也会抛出错误
我还是编程新手,这让我很困惑。尝试为
字符串和int
s创建单独的Scanner
s。Java扫描器在使用它进行多种类型的读取时,往往会表现出奇怪的行为。请记住,如果通过nextLine()进行读取,则不需要使用剩余的换行符
-换行符是此实例中的分隔符,它是consumedUsenext
而不是nextLine
来使用无效令牌nextLine
尝试读取数据,直到下一行分隔符或流结束,但nextLine
不使用行分隔符。
You have chosen to edit a book.
Enter the ID of the book you would like to edit:
1
You are about to edit: Harry Potter and the Chamber of Secrets by J.K. Rowling
Please enter the book's new title:
Harry Potter
Please enter the book's new author:
J.K Rowling
How many books do you have?:
Enter an integer!
1
How many books currently on loan? (Enter 0 if none):
0
How many times has this book been loaned out? (Enter 0 if never):
0
The new details of this book are: ID: 0Title: Author: Potter Quantity: 1 No. on Loan: 0 No. of times loaned: 0