所以我有一个 addItem() 方法,我可以在其中将一本书、磁带或 cd 对象添加到我的库存中。为了存储书籍、磁带或 cd 对象,我从用户那里获取对象的标题、作者和价格。但是,当我运行该程序时,它会跳过“请输入标题:”并向右转到“请输入作者:”。然后当我让它显示信息时,标题字段为“空”。
static void addItem(int type) {
String title;
String author;
Double price;
System.out.println("Please enter the title");
title = keyboard.nextLine()
System.out.println("Please enter the author");
author = keyboard.nextLine();
System.out.println("Please enter the price");
price = keyboard.nextDouble();
if(type == 0){
Book BookStoreItem;
BookStoreItem = new Book(title, author, price);
System.out.println("You've entered:");
System.out.println("Title: " + BookStoreItem.getTitle());
System.out.println("Author: " + BookStoreItem.getAuthor());
System.out.println("Price: " + BookStoreItem.getPrice());
}
if(type == 1){
Tape BookStoreItem;
BookStoreItem = new Tape(title, author, price);
System.out.println("You've entered:");
System.out.println("Title: " + BookStoreItem.getTitle());
System.out.println("Author: " + BookStoreItem.getAuthor());
System.out.println("Price: " + BookStoreItem.getPrice());
}
if(type == 2){
CD BookStoreItem;
BookStoreItem = new CD(title, author, price);
System.out.println("You've entered:");
System.out.println("Title: " + BookStoreItem.getTitle());
System.out.println("Author: " + BookStoreItem.getAuthor());
System.out.println("Price: " + BookStoreItem.getPrice());
}
}//end of addItem()
这是一个示例输出:
Press:
0 To add a book to the inventory
1 To add a tape to the inventory
2 To add a Cd to the inventory
Please enter your choice: 0
Please enter the title:
Please enter the author: John Smith
Please enter the price: 55.50
Title: null
Author: John Smith
Price: 55.5
这是菜单上的更新:
static void printMenu() {
System.out.println("\nPress:");
System.out.println("\t" + ADD_BOOK + "\tTo add a book to the inventory\n");
System.out.println("\t" + ADD_TAPE + "\tTo add a tape to the inventory\n");
System.out.println("\t" + ADD_CD + "\tTo add a CD to the inventory\n");
System.out.println("\t" + SHOW_ITEM_LIST + "\tTo display a list of available books\n");
System.out.println("\t" + SEARCH_ITEM + "\tTo search for a specific book\n");
System.out.println("\t" + QUIT + "\tTo exit\n");
}
并有选择:
static void runBookStoreApplication() {
int userChoice = QUIT;
String quitMessage = "\nThank you for using the BookStoreApplication!";
String invalidOptionMessage = "\nInvalid option!";
do{
printMenu();
userChoice = getUserChoice();
switch (userChoice) {
case ADD_BOOK:
addItem(0);
break;
case ADD_TAPE:
addItem(1);
case ADD_CD:
addItem(2);
case SHOW_ITEM_LIST:
showItemList();
break;
case SEARCH_ITEM:
searchItem();
break;
case QUIT:
System.out.println(quitMessage);
break;
default:
System.out.println(invalidOptionMessage);
}
} while(userChoice != QUIT);
}//end of runBookStoreApplication
使用 getUserChoice:
static int getUserChoice() {
int choice;
System.out.print("Please enter your choice: ");
choice = keyboard.nextInt();
return choice;
}