我正在设计一个地址簿,为了使我的 AddressBookApp 类工作(包括我的主要方法),我必须创建实例变量并将它们设为静态,以便我的类中的每个方法都能够访问我的姓名、电子邮件, 和 Phone 对象。我认为有更好的方法,但我很难知道那是什么。我应该在 main 方法中创建对象吗?实例变量是正确的方法吗?你们对我如何改进我的设计有什么想法吗?(如果您有任何其他与我的问题无关的设计建议,请告诉我)
这是我的 AddressBookApp 类的代码:
import java.util.Scanner;
public class AddressBookApp {
//Instance Variables
private static Name name;
private static Email email;
private static Phone phone;
//Constructor
public AddressBookApp() {
name = new Name();
email = new Email();
phone = new Phone();
}
//Main method
public static void main(String[] args) {
new AddressBookApp();
System.out.println("Welcome to the Address Book Application\n");
Scanner sc = new Scanner(System.in);
int menuNumber;
do {
menu();
menuNumber = sc.nextInt();
System.out.println();
if (menuNumber < 1 || menuNumber > 4){
System.out.println("Please enter a valid menu number\n");
} else if (menuNumber == 1) {
printEntries();
} else if (menuNumber == 2) {
addEntry();
} else if (menuNumber == 3) {
removeEntry();
} else {
System.out.println("Thanks! Goodbye.");
sc.close();
return;
}
continue;
} while (menuNumber != 4);
sc.close();
}
/**
* Prints out Main Menu
*/
public static void menu() {
System.out.println("1 - List entries\n" +
"2 - Add entry\n" +
"3 - Remove entry\n" +
"4 - Exit\n");
System.out.print("Enter menu Number: ");
}
/**
* Prints all entries in the Address Book
*/
public static void printEntries() {
name.printNames();
System.out.println();
email.printEmails();
System.out.println();
phone.printPhoneNumbers();
System.out.println();
}
/**
* Adds an entry to the Address Book
*/
public static void addEntry() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Name: ");
name.addName(sc.nextLine());
System.out.print("Enter Email Address: ");
email.addEmail(sc.nextLine());
System.out.print("Enter Phone Number: ");
phone.addPhone(sc.nextLine());
System.out.println("\nRecord Saved.\n");
}
/**
* Removes and entry from the Address Book
*/
public static void removeEntry() {
Scanner sc = new Scanner(System.in);
System.out.print("Please Enter the record number that you would like to remove: ");
int records = sc.nextInt();
name.removeNames(records - 1);
email.removeEmail(records - 1);
phone.removePhone(records - 1);
}
}