我正在使用具有编辑书方法的图书馆应用程序,但目前我遇到了让它做我想做的事的问题。这是我到目前为止所拥有的;
editBook()方法;
public void editBook(int ID, String title, String author, int quantity, int numOnLoan, int numTimesLoaned) {
int i = 0;
this.myLibrary.get(i).setTitle(title);
this.myLibrary.get(i).setAuthor(author);
this.myLibrary.get(i).setQuantity(quantity);
this.myLibrary.get(i).setNumOnLoan(numOnLoan);
this.myLibrary.get(i).setNumTimesLoaned(numTimesLoaned);
//The new details of the book are printed out below to confirm the details that the user has entered
System.out.println("The new details of this book are: " + "ID: " + this.myLibrary.get(i).getID() +
"Title: " + this.myLibrary.get(i).getTitle() + " Author: " +
this.myLibrary.get(i).getAuthor() + " Quantity: " + this.myLibrary.get(i).getQuantity() + " No. on Loan: " +
this.myLibrary.get(i).getNumOnLoan() + " No. of times loaned: " + this.myLibrary.get(i).getNumTimesLoaned());
然后这是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 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,标题或作者被存储以及"数量"的输入。即使我没有输入任何内容,也会抛出错误。
我还是编程新手,这让我很困惑。
答案 0 :(得分:-3)
尝试为Scanner
和String
创建单独的int
。当使用Java Scanner
读取多种类型时,它会出现奇怪的行为。