我正在编写一个main方法来为我正在为我正在学习的java类编写的Contact类和ContactBook类提供一个菜单。我的问题是,我希望当用户输入A,F,P或Q时,我的扫描仪对象(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课程。我检查了很多资源,试图了解我做错了什么,而且我无法将它拼凑在一起。希望有人可以为我阐明这一点。感谢。
答案 0 :(得分:3)
我会删除对kbd.next()
的所有来电并替换kbd.nextLine()
。这里没有必要使用next()
,因为它不处理行结束令牌,所以它会让你感到困惑。如果您绝对需要使用kbd.next()
,请务必在致电kbd.nextLine()
后致电next()
,以允许您的程序以合理的方式处理行结束令牌。