I'm trying to call addContact method from main method using ArrayList called phone but its not working.
Here's the code:
import java.util.ArrayList;
import java.util.Scanner;
class A {
String name;
int num;
Scanner sc = new Scanner(System.in);
public A(String name, int num) {
this.name= name;
this.num= num;
}
public void addContact() {
sc.nextLine();
System.out.println("Enter name:");
name = sc.nextLine();
System.out.println("Enter number:");
num = sc.nextInt();
}
}
public class Main {
static void menu() {
System.out.println("1. add");
System.out.println("2. break");
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList <A> phone;
while(true) {
menu();
int c = sc.nextInt();
if(c==1) {
phone.add().addContact();
//I'm trying to call addContact()
} else if(c==2) {
break;
}
}
}
}
Why I can't just call phone.add().addContact()?
import java.util.ArrayList;
import java.util.Scanner;
class A {
String name;
int num;
Scanner sc = new Scanner(System.in);
public A(String name, int num) {
this.name= name;
this.num= num;
}
}
public class Main {
static void menu()
{
System.out.println("1. add");
System.out.println("2. break");
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList <A> phone = new Arraylist<A>();
while(true)
{
menu();
int c = sc.nextInt();
if(c==1)
{
System.out.println("Enter name:");
String name = sc.nextLine();
System.out.println("Enter number:");
int num = sc.nextInt();
phone.add(new A(name,num));
}
else if(c==2)
{
break;
}
}
}
}
Just removed you addContact and placed in in the while. Now i create a new Instance of A and add it to the list. This should work now. Please post more precise Questions in the future.
You need to create an instance of your list:
ArrayList<A> phone = new ArrayList<>();
ArrayList <A> phone;
Should be:
ArrayList phone = new ArrayList();
Also, the add() method in this line
phone.add().addContact();
should contain an A object to add to the ArrayList.
you need to return object of A
public A addContact() {
sc.nextLine();
System.out.println("Enter name:");
name = sc.nextLine();
System.out.println("Enter number:");
num = sc.nextInt();
return new A(name,num);
}
and
if(c==1)
{
phone.add(addContact);
}
Your problem starts here:
ArrayList <A> phone;
only declares that list; but doesnt define it. Thus you run into a NullPointerException when you try to run your code.
You need
ArrayList <A> contacts = new ArrayList<>();
instead. I took the freedom to give that variable a reasonable name, too. (this list is about storing contents, it is not storing phones; and it is also not a single phone ... just a list of contact information)
But there is more. You see, you are getting your abstractions wrong. Your Contact class (A is just a terrible name for that class) should not be dealing with a scanner to fetch its data.
Instead, you want to do something like:
class Contact {
private final String name;
private final int number;
Contact(String name, int number) {
this.name = name;
this.number = number;
}
and then, within your main method, you do something like:
boolean loop = true;
while (loop) {
... have user enter a name and a number
if (name.equals("STOP")) {
loop = false;
} else {
Contact contact = new Contact(name, number);
phones.add(contact);
}
}
I can't give the working code. Just check below points to make your program better.
Why you are creating constructor with arguments when you using add contact method.
Where you are created object for class A in class Main.
Try to check how to use ArrayList class. Because you are not using add() properly.
Related
//Main :
package DevAyo;
import java.util.Scanner;
public class Main {
private static Scanner scanner =new Scanner(System.in);
private static Album Alb =new Album("Kamikaze");
public static void main(String[] args) {
boolean quit = true;
while (quit){
System.out.println("Choose actions : ");
System.out.println("\t\t 1.Add new Songs to Album :");
System.out.println("\t\t 2.printSongs");
System.out.println("\t\t 3.Quit");
System.out.println("choose Action : ");
int choice = scanner.nextInt();
scanner.nextLine();
switch (choice){
case 1:
AddSong();
break;
case 2:
Alb.printSongs();
break;
case 3:
quit=false;
break;
}
}
}
public static void AddSong(){
// System.out.println("Insert Album Name: ");
// String albumName =scanner.nextLine();
System.out.println("Pleas Enter Number of Songs :");
int Number = scanner.nextInt();
for (int i=0;i<Number;i++){
System.out.println("Enter Song Name "+(i+1)+": ");
String name=scanner.nextLine();
scanner.nextLine();
System.out.println("Enter Singer of Song "+(i+1)+": ");
String SingerName =scanner.nextLine();
System.out.println("Enter Song "+(i+1)+" released Day: ");
String ReleasedDay = scanner.nextLine();
System.out.println("Enter Length of the Song"+(i+1)+": ");
int SongLength=scanner.nextInt();
Songs song = Songs.creatSong(name,SingerName,ReleasedDay,SongLength);
if(Alb.addSOngs(song))
System.out.println("Songs added ! ");
else
System.out.println("Error ! ");
}
}`enter code here`
}
//Album Class
package DevAyo;
import java.util.ArrayList;
import java.util.Scanner;
public class Album {
public String AlbumName;
private static Scanner scanner = new Scanner(System.in);
ArrayList<Songs> ListofSongs;
public Album(String albumName) {
AlbumName = albumName;
this.ListofSongs=new ArrayList<Songs>();
}
public boolean addSOngs(Songs song){
if(findSong(song.getSongName())>=0){
System.out.println("Songs aLready Exisit ! ");
return false;
}
ListofSongs.add(song);
return true;
}
private int findSong(String songName){
for(int i=0; i<ListofSongs.size();i++){
Songs song = ListofSongs.get(i);
if(song.getSongName().equals(songName)){
return i;
}
}
return -1;
}
public void printSongs(){
for(int i=0;i<this.ListofSongs.size();i++){
System.out.println("Song Name: "+ this.ListofSongs.get(i).getSongName()+"\n"
+"Singer: "+this.ListofSongs.get(i).getSongSinger()+"\n"+"Song Released Day: "+this.ListofSongs.get(i).getSongDay()+
"\n"+"Song Length: "+this.ListofSongs.get(i).songLength+" min");
}
}
}
//Songs Class
package DevAyo;
public class Songs {
public static String songName;
public static String songSinger;
public static String songDay;
public static int songLength;
public Songs(String songName, String songSinger, String songDay, int songLength) {
this.songName = songName;
this.songSinger = songSinger;
this.songDay = songDay;
this.songLength = songLength;
}
public String getSongName() {
return this.songName;
}
public String getSongSinger() {
return this.songSinger;
}
public String getSongDay() {
return this.songDay;
}
public int getSongLength() {
return this.songLength;
}
public static Songs creatSong(String name, String singerName, String releasedDay, int songLength){
return new Songs(songName,songSinger,songDay,songLength);
}
}
i just tried so many was i can't undrestand why it displlays null , i 've created the constructor in both classes and still dosen't seem to work, honestly i've searched the internet about the problem but it's says that i should add constructor i've add them but nothing happpen anyway hope the code is clear , hope you guys can help thanks .
After a Scanner.nextInt(); leaves an empty line so the next time you call Scanner.nextLine(); it will give you that empty line.
If you want to avoid this, you could do one of this 2 options:
Parse
Always use Scanner.nextLine() and cast to the type of variable you want.
Example: int a = Integer.parseInt(scanner.nextLine());
Read that empty line
always you use the nextInt() immediately call nextLine()
Example:
int a = scanner.nextInt();
scanner.nextLine()
I try to write a code which will have a basic menu with some options. These options are the following methods: AddStudent, changeName, setGrade and so on. I have created an object called Student which has a name, a grade and an age. I want to add Students in an linked list but when I use the method add it does not work. Here is my code:
import java.util.*;
class Student {
int age;
int grade;
String name;
static LinkedList ll = new LinkedList();
public Student (String n) { //we create here a student with a name and an age
name=n;
age=0;
grade=0;
}
//-------------------------------------------------------------------------
public void p(String x) {
System.out.println(x);
}
public void addStudent() {
Scanner s = new Scanner(System.in);
p("Enter the name that you want");
String f = s.nextLine();
Student a = new Student(f);
ll.add(a);
}
public void changeName() { //this method is to change the name of a student
Scanner s = new Scanner(System.in);
p("Enter whose name you want to change");
String c = s.nextLine();
p("Enter the name that you want");
String b = s.nextLine();
}
public void setGrade(Student a) { //this method is to put the student's grade
Scanner s = new Scanner(System.in);
p("Enter the grade that you want");
int g = s.nextInt();
a.grade=g;
}
public void setAge(Student a) { //This method is to put the student's grade
Scanner s = new Scanner(System.in);
p("Enter the age that you want");
int h = s.nextInt();
a.age=h;
}
public String getName(Student a) {
return a.name;
}
public int getAge(Student a) {
return a.age;
}
public int getGrade(Student a) {
return a.grade;
}
}
The problem is at the method of addStudent. Is there any other ways,as well, with which I can make the same project?
Think about this logically. You have a Student class that represents a single Student. Why would a Student have a List of Student's? That makes no sense.
Wouldn't you have a program like Course or something that would hold the list of Students? That is where your List belongs. And don't use static unless you have a compelling reason (rare).
Here is a start for the Course class, that uses the Student to store student information and stores it in your LinkedList within the Course. You still need to implement the findStudent method and probably a method to print the List:
Class Course:
import java.util.LinkedList;
import java.util.Scanner;
public class Course {
LinkedList ll = new LinkedList();
Scanner s = new Scanner(System.in);
public void addStudent() {
p("Enter the name that you want");
String f = s.nextLine();
Student a = new Student(f);
ll.add(a);
}
public void changeName() { //this method is to change the name of a student
Student student = findStudent();
p("Enter the name that you want");
String newName = s.nextLine();
//student.setName(newName);
}
public void setGrade() { //this method is to put the student's grade
Student student = findStudent();
p("Enter the grade that you want");
int grade = s.nextInt();
//student.setGrade(grade);
}
public void setAge() { //This method is to put the student's grade
Student student = findStudent();
p("Enter the age that you want");
int age = s.nextInt();
student.setAge(age);
}
public Student findStudent(){
p("Which student did you want to change? Please enter their name:");
String name = s.nextLine();
//Find student in the list - left for the author
Student student = null;
return student;
}
//-------------------------------------------------------------------------
public void p(String x) {
System.out.println(x);
}
public static void main(String[] args) {
Course course = new Course();
course.addStudent();
course.addStudent();
course.changeName();
course.setGrade();
}
}
And the modified Student class:
import java.util.*;
public class Student {
int age;
int grade;
String name;
public Student (String n) { //we create here a student with a name and an age
name=n;
age=0;
grade=0;
}
public void setName(String name) {
this.name = name;
}
public void setGrade(int grade) {
this.grade = grade;
}
public void setAge(int age) {
this.age = age;
}
public String getName(Student a) {
return a.name;
}
public int getAge(Student a) {
return a.age;
}
public int getGrade(Student a) {
return a.grade;
}
#Override
public String toString(){
return "Student(name:" + name + ", age:" + age + ", grade:" + grade + ")";
}
}
This code is kind of messy because you include some code that shouldn't appear in Student class. For example, the addStudent method is not static and in order to call it, you need to first instantiate an instance of Student and call the method on it. However, the method is trying to ask user to input the information of a new Student instance, which is a bad design.
So, keep the Student class only do what it should do. For your case, Student only need to store its age, grade and name fields and define constructors to initialize these fields, and optional getter and setter methods to set and retrieve these fields upon your needs.
You will need a 'manager' class which manages your application. This class will keeps track of a list of students, and asks users to input information of a new student and then initialize the student instance and put it in the list. This Manager class can even manage an UI which you need to take user input or display information to the user. So, it will be this class's responsibility to provide a addStudent method.
Student class itself should know nothing about your application's logic like it may be a course selection program or something else. It only manages its own information while some manager class will take care of the application's logic.
Can't take my head around the following: There are 2 classes - "Item", where attributes (Name, Price) and constructors are set, and main "Store". In the last one - Arraylist, which fills up with Items depending on user input. The code works.
Here is the question: Is there any way to put all from the main class, apart from "ArrayList listOfItems=new ArrayList();" line into a method "addItem()" and then just call the method? I do not know how to do it. Tried a lot.
Thank you
package store;
import java.util.ArrayList;
import java.util.Scanner;
public class Store extends Item {
public static void main(String[] args) {
ArrayList<Item> listOfItems=new ArrayList<Item>();
for(int i=0;i<2;i++){
System.out.println("ENTER NAME");
Scanner addName=new Scanner (System.in);
String name=(addName.nextLine());
System.out.println("ENTER PRICE");
Scanner addPrice=new Scanner (System.in);
double price=(addPrice.nextDouble());
listOfItems.add(new Item(name,price));
}
for(Item list:listOfItems){
System.out.println("NAME "+list.getName()+", PRICE "+list.getPrice());
}
}
}
This will work for you:
package store;
import java.util.ArrayList;
import java.util.Scanner;
public class Store {
private static class Item {
private String name;
private double price;
public Item(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
}
public static void main(String[] args) {
ArrayList<Item> listOfItems = new ArrayList<Item>();
addItem(listOfItems);
}
private static void addItem(ArrayList<Item> listOfItems) {
for (int i = 0; i < 2; i++) {
System.out.println("ENTER NAME");
Scanner addName = new Scanner(System.in);
String name = (addName.nextLine());
System.out.println("ENTER PRICE");
Scanner addPrice = new Scanner(System.in);
double price = (addPrice.nextDouble());
listOfItems.add(new Item(name, price));
}
for (Item list : listOfItems) {
System.out.println("NAME " + list.getName() + ", PRICE " + list.getPrice());
}
}
}
I defined the class Item separately to make it compiling. Also I removed the extends Item from the store, because it is not needed.
I don't know exactly if this is what you are looking for, but you may try the following solution:
public class Store extends Item {
public static void main(String[] args) {
ArrayList<Item> listOfItems=new ArrayList<Item>();
addItem(listOfItems);
for(Item list:listOfItems){
System.out.println("NAME "+list.getName()+", PRICE "+list.getPrice());
}
}
private static void addItem(ArrayList<Item> li) {
for(int i=0;i<2;i++){
System.out.println("ENTER NAME");
Scanner addName=new Scanner (System.in);
String name=(addName.nextLine());
System.out.println("ENTER PRICE");
Scanner addPrice=new Scanner (System.in);
double price=(addPrice.nextDouble());
li.add(new Item(name,price));
}
}
}
You maybe also try to declare the ArrayList outside the main:
public class Store extends Item {
private static ArrayList<Item> listOfItems;
public static void main(String[] args) {
listOfItems=new ArrayList<Item>();
addItem();
for(Item list:listOfItems){
System.out.println("NAME "+list.getName()+", PRICE "+list.getPrice());
}
}
private static void addItem() {
for(int i=0;i<2;i++){
System.out.println("ENTER NAME");
Scanner addName=new Scanner (System.in);
String name=(addName.nextLine());
System.out.println("ENTER PRICE");
Scanner addPrice=new Scanner (System.in);
double price=(addPrice.nextDouble());
listOfItems.add(new Item(name,price));
}
}
}
Let me know if you need further help! :)
You could use a better Oriented Object approach to solve your problem.
Store extends Items this has not sense. The store contains items, so you only need a variable like your listOfItems for save all the items of the store.
Your public class Store is a good candidate to use the Singleton Pattern.
About the construction of your listOfItems: When a List is enough, then simply you should use just a List. Also, java 7 provide the type inference for generic instance creation.
From The Java SE Documentation: You can replace the type arguments required to invoke the constructor of a generic class with an empty set of type parameters (<>) as long as the compiler can infer the type arguments from the context. This pair of angle brackets is informally called the diamond.
So, you should use List<Item> listOfItems = new ArrayList<>() instead of ArrayList<Item> listOfItems = new ArrayList<Item>()
Each time that you use a Scanner you should close it.
The Singleton:
public class Store {
private static final Store INSTANCE = new Store();
private List<Item> listOfItems = new ArrayList<>();
private Store() {
// Private Constructor
// will prevent the instantiation of this class directly
}
public static Store getInstance() {
return INSTANCE;
}
public void addItems(List<Item> newlistOfItems) {
listOfItems.addAll(newlistOfItems);
}
public String printListOfItems() {
StringBuilder sb = new StringBuilder();
for (Item item : listOfItems) {
sb.append(" [NAME : " + item.getName() + ", PRICE : " + item.getPrice() + "]");
}
return sb.toString();
}
}
The POJO Item class
public class Item {
private String name;
private double price;
public Item(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
}
The service interface for the management of items :
public interface ItemManagerService {
List<Item> createListOfItems();
}
The implementation:
public class ItemManagerServiceImpl implements ItemManagerService {
#Override
public List<Item> createListOfItems() {
List<Item> newListOfItems = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
try {
do {
System.out.println("ENTER NAME");
String name = scanner.nextLine();
System.out.println("ENTER PRICE");
while (!scanner.hasNextDouble()) {
System.out.print("You must enter a valid number! Try again: ");
scanner.next();
}
double price = scanner.nextDouble();
Item item = new Item(name, price);
newListOfItems.add(item);
System.out.println("Continue?[Y/N]");
scanner.nextLine();
} while (scanner.nextLine().equalsIgnoreCase("y"));
} finally {
scanner.close();
}
return newListOfItems;
}
}
A simple test :
public class MainApp {
public static void main(String[] args) {
ItemManagerService itemManagerService = new ItemManagerServiceImpl();
List<Item> newlistOfItems = itemManagerService.createListOfItems();
Store.getInstance().addItems(newlistOfItems);
System.out.println(Store.getInstance().printListOfItems());
}
}
The console output:
ENTER NAME
table
ENTER PRICE
12
Continue?[Y/N]
y
ENTER NAME
car
ENTER PRICE
50,8
Continue?[Y/N]
n
[NAME : table, PRICE : 12.0] [NAME : car, PRICE : 50.8]
I have been stuck on the same problem for days and have googled everything I can think of and I give up. I am trying to write a program where you're supposed to first create a person object, and afterwards be able to give that person different types of belongings. I'm putting each created person in an arraylist and every person is supposed to have their own inventory which is also an arraylist. I just don't understand how to add items to a specific persons arraylist and how to print that arraylist. Do I have to create a new instance of the arraylist 'belongings' every time I create a new person? and how do I access a certain persons arraylist? Appreciate any sort of feedback because I am super noob.
import java.util.ArrayList;
public class Sakregister extends Programskelett{
public static ArrayList<Person> personList = new ArrayList<Person>();
protected boolean nextCommand(){
String command = readString("> ").toLowerCase();
switch(command){
case "print list":
printAll();
System.out.println("Program is running");
break;
case "print person":
printUser();
System.out.println("Program is running");
break;
case "create item":
newItem();
break;
case "create user":
newUser();
break;
case "print richest":
printRichest();
System.out.println("Program is running");
break;
case "crash":
initCrash();
break;
case "quit":
System.out.println("Program has terminated");
return true;
default:
System.out.println("Not a valid command");
}
return false;
}
private void printAll() {
}
private void initCrash() {
for (Person thisPerson : personList) {
for (Item thisItem : thisPerson.belongings)
if (thisItem.name == "Stock"){
((Stock) thisItem).setStockCrash(0);
}
}
}
private void printRichest() {
}
private void newUser() {
System.out.println("enter name: ");
String name = keyboard.nextLine();
Person newPerson = new Person(name);
personList.add(newPerson);
System.out.println("Person added to list");
}
private boolean newItem() {
System.out.println("enter item type: ");
String itemType = readString("> ").toLowerCase();
switch(itemType){
case "trinket":
addTrinket();
break;
case "stock":
addStock();
break;
case "appliance":
addAppliance();
return true;
default:
System.out.println("Not a valid item type");
}
return false;
}
private void addAppliance() {
System.out.println("Enter name of appliance: ");
String appName = keyboard.nextLine();
System.out.println("Enter initial price: ");
int appInitialPrice = keyboard.nextInt();
System.out.println("Enter level of wear: ");
int appWear = keyboard.nextInt();
Appliance newAppliance = new Appliance(appName, appInitialPrice, appWear);
System.out.println("Enter name of owner: ");
Object owner = keyboard.nextLine();
for(Person entry : personList)
if(entry.equals(owner))
entry.belongings.add(newAppliance);
}
private void addStock() {
System.out.println("Enter name of stock entry: ");
String stockName = keyboard.nextLine();
System.out.println("Enter amount: ");
int stockAmount = keyboard.nextInt();
System.out.println("Enter price: ");
int stockPrice = keyboard.nextInt();
Stock newStock = new Stock(stockName, stockAmount, stockPrice);
System.out.println("Enter name of owner: ");
String owner = keyboard.nextLine();
keyboard.nextLine();
for(Person entry : personList) {
if(entry.equals(owner)) {
entry.belongings.add(newStock);
}
}
}
private void addTrinket() {
System.out.println("Enter name of trinket: ");
String trinketName = keyboard.nextLine();
System.out.println("Enter number of gems: ");
int trinketGems = keyboard.nextInt();
System.out.println("Choose gold or silver: ");
String trinketMineral = keyboard.nextLine();
keyboard.nextLine();
Trinket newTrinket = new Trinket(trinketName, trinketGems, trinketMineral);
System.out.println("Enter name of owner: ");
String owner = keyboard.nextLine();
for(Person entry : personList)
if(entry.equals(owner))
entry.belongings.add(newTrinket);
}
private void printUser() {
// TODO Auto-generated method stub
}
protected void printMainMenu(){
System.out.println("Choose a command: ");
System.out.println("start");
System.out.println("quit");
}
public static void main(String[] args) {
Sakregister registerProgram = new Sakregister();
registerProgram.run();
}
}
public class Item{
protected String name;
public Item(String name){
this.name = name;
}
public String getItemName() {
return name;
}
import java.util.ArrayList;
public class Person{
public String name;
public String items;
public ArrayList<Item> belongings = new ArrayList<Item>();
public Person(String name){
this.name = name;
}
public String getName(){
return name;
}
public String toString() {
return "Name: " + name;
}
}
" I just don't understand how to add items to a specific persons arraylist and how to print that arraylist"
Your persons are in the personList, so i would use personList.get(n) to get the nth Person.
To add items to the belongings you can use personList.get(n).belongings.add(item).
To print an arraylist you can use a normal foreach loop:
for(Item i:personList.get(n).belongings){
System.out.println(i.getItemName());
}
Do I have to create a new instance of the arraylist 'belongings' every time I create a new person?
The ArrayList belongings is a field inside the Person class. When you create a person with the constructor all of its fields and variables are created in the memory. This happens every time you create a person, so every object (in your case person in the personList) has its own fields like the belongings list.
The new instance of the ArrayList<Item> belongings is already being created each time you create a new Person object, so you don't need to create it again anywhere. However, there is currently no getter for belongings, so you need to write one to access a given person's belongings. You want something like this:
public ArrayList<Item> getBelongings() {
return belongings;
}
You'll need to write a public method that accepts an Item object and adds it to the belongings of that Person. You shouldn't need help with writing another public method that calls System.out.println() on the belongings directly or iterates through them and prints them out.
I am designing an Address Book and in order to make my AddressBookApp class work (which includes my main method) I have had to create instance variables and make them static in order for each method in my class to be able to access my Name, Email, and Phone objects. I assume that there is a better way, but am struggling to know what that is. Should I create the objects in the main method? Are instance variables the right way to go? Do you guys have any ideas as to how I can improve my design? (If you have any other design suggestions not related to my question then let me know)
Here is the code for my AddressBookApp class:
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);
}
}
AddressBook and AddressBookApp should be two different classes. AddressBook should look like this:
public class AddressBook {
//Instance Variables
private Name name;
private Email email;
private Phone phone;
//Constructor
public AddressBook() {
name = new Name();
email = new Email();
phone = new Phone();
}
// more Constructors
public void setName(Name name) {
this.name = name
}
public Name getName() {
return name;
}
// more getters and setters
Your app can then create an instance of this in your main() method:
AddressBook book = new AddressBook();
book.setName(new Name("Jeff"));
//more operations on book
You can pass around the object book to any methods in which you need it or keep creating new instances. You can also have it as a static reference in your app class:
private static AddressBook book = new AddressBook();
// in your app class methods
book.burnBeforeReading();
Simple, create two classes: Main and AddressBook.
Main only has
public static void main(String[] args) {
new AddressBook().execute();
...
AddressBook only has instance methods.