2
我正在寫一個主要方法,爲我爲我正在使用的java類編寫的Contact類和ContactBook類提供菜單。我的問題是,我期望當用戶輸入我的掃描儀對象(kbd)捕獲輸入的A,F,P或Q時,使用它,並在輸入下一個輸入後繼續。顯然有一些我不理解的關鍵,因爲推遲返回並不總是像我預料的那樣推進我的計劃。我已經包含了我的代碼和輸出。任何提示將非常感謝。Java家庭作業 - 使用next()和nextLine()方法的掃描儀對象
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:
[email protected]
//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:
[email protected]
a
s
d
A - Add a contact
F - Find a contact
P - Prints the list
Q - Quits
再次,我是一名學生,這是我的第二個Java類。我已經檢查了很多資源,試圖瞭解我做錯了什麼,而且我一直無法將它拼湊在一起。希望有人能爲我闡明這一點。謝謝。
不要在每個if語句中調用next()。 –
@Shakedown:你的評論應該擴大,應該是一個答案。僅僅是一個評論就太好了。 –