我正在编写一个主要方法来为我为正在使用的 java 类编写的 Contact 类和 ContactBook 类提供菜单。我的问题是,我希望当用户输入 A、F、P 或 Q 时,我的 Scanner 对象 (kbd) 会捕获输入,使用它,并在输入下一个输入后继续前进。显然有一些我不理解的关键,因为推动返回并不总是像我预期的那样推进我的程序。我已经包含了我的代码和输出。任何提示将非常感谢。
import java.util.Scanner;
public class run{
public static void main(String[]args){
Scanner kbd = new Scanner(System.in);
boolean quit = false;
System.out.println("How many contacts would you like in your Contact Book?: ");
int size = kbd.nextInt();
kbd.nextLine();
ContactBook kevin = new ContactBook(size);
while(!quit){
System.out.println("A - Add a contact \n"+
"F - Find a contact \n"+
"P - Prints the list \n"+
"Q - Quits");
if(kbd.next().equals("A")){
if(ContactBook.full(kevin))
System.out.println("Contact book full!");
else{
Contact temp = new Contact();
System.out.println("Enter a First Name: ");
temp.setFirstName(kbd.nextLine());
System.out.println("Enter a Last Name: ");
temp.setLastName(kbd.nextLine());
System.out.println("Enter a Phone Number: ");
temp.setPhoneNumber(kbd.nextLine());
System.out.println("Enter an email: ");
temp.setEmail(kbd.nextLine());
kevin.addContact(temp);
}
}
if(kbd.next().equals("F")){
kevin.search();
}
if(kbd.next().equals("P")){
System.out.print(kevin.produce());
}
if(kbd.next().equals("Q")){
quit = true;
}
}
}
}
这是我得到的输出。
----jGRASP exec: java run
How many contacts would you like in your Contact Book?:
3
A - Add a contact
F - Find a contact
P - Prints the list
Q - Quits
A
Enter a First Name:
Kevin
Enter a Last Name:
Smith
Enter a Phone Number:
312-4567
Enter an email:
kevin@gmail.com
//here I keep pushing enter and am not sure why it doesn't continue back to
//the beginning of my while loop
a
a
a
A - Add a contact
F - Find a contact
P - Prints the list
Q - Quits
a
----jGRASP: process ended by user.
----jGRASP exec: java run
How many contacts would you like in your Contact Book?:
----jGRASP: process ended by user.
----jGRASP exec: java run
How many contacts would you like in your Contact Book?:
4
A - Add a contact
F - Find a contact
P - Prints the list
Q - Quits
A
Enter a First Name:
Enter a Last Name:
Smith
Enter a Phone Number:
312-4567
Enter an email:
kevin@gmail.com
a
s
d
A - Add a contact
F - Find a contact
P - Prints the list
Q - Quits
同样,我是一名学生,这是我的第二堂 Java 课。我检查了许多资源,试图了解我做错了什么,但我无法将其拼凑起来。希望有人可以为我阐明这一点。谢谢。