ArrayList and object issue - java

I tried to create ArrayList with Ingredients object and then iterate through this list but this is only showing the last added ingredient. For example when I'm adding two ingredients (mushrooms, tomatoes) in arrayList are only tomatoes with index 0 and 1.
import java.util.ArrayList;
import java.util.List;
public class Ingredients {
private String ingredientName;
private int ingriedientQuantity;
List<Ingredients> ingredients;
public Ingredients() {
this.ingredients = new ArrayList<>();
}
public void addIngredient(Ingredients ingredient) {
ingredients.add(ingredient);
}
public String getIngredientName() {
return ingredientName;
}
public void setIngredientName(String ingredientName) {
this.ingredientName = ingredientName;
}
public int getIngriedientQuantity() {
return ingriedientQuantity;
}
public void setIngriedientQuantity(int ingriedientQuantity) {
this.ingriedientQuantity = ingriedientQuantity;
}
public void showIngredients() {
for (Ingredients ingredientI : ingredients) {
System.out.println(ingredientI.getIngredientName() + " " + ingredientI.getIngriedientQuantity());
}
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Ingredients ing = null;
boolean exitFlag = false;
String name;
int quantity;
int option = 0;
String o;
while (!exitFlag) {
System.out.println("1 - Add");
System.out.println("2 - Show");
System.out.println("3 - Exit");
option = sc.nextInt();
sc.nextLine();
switch (option) {
case 1:
ing = new Ingredients();
do {
System.out.println("Product name: ");
name = sc.nextLine();
ing.setIngredientName(name);
System.out.println("Quantity");
quantity = sc.nextInt();
sc.nextLine();
ing.setIngriedientQuantity(quantity);
System.out.println("Add more? Y/N");
o = sc.nextLine();
ing.addIngredient(ing);
} while (!o.equalsIgnoreCase("N"));
break;
case 2:
ing.showIngredients();
break;
case 3:
exitFlag = true;
break;
default:
System.out.println("Error");
break;
}
}
sc.close();
}
}
Is better way to do it?

Your class design is wrong. Create a separate class Ingredient with properties IngredientName and IngredientQuantity. The Ingredients class maintains an ArrayList for Ingredient objects.
A sample Ingredient class may look like:
import java.util.ArrayList;
import java.util.List;
public class Ingredient {
private String ingredientName;
private int ingriedientQuantity;
public Ingredient() {
}
public String getIngredientName() {
return ingredientName;
}
public void setIngredientName(String ingredientName) {
this.ingredientName = ingredientName;
}
public int getIngriedientQuantity() {
return ingriedientQuantity;
}
public void setIngriedientQuantity(int ingriedientQuantity) {
this.ingriedientQuantity = ingriedientQuantity;
}
}
Your Ingredients can be implemented as:
import java.util.ArrayList;
import java.util.List;
public class Ingredients {
List<Ingredient> ingredients;
public Ingredients() {
this.ingredients = new ArrayList<Ingredient>();
}
public void addIngredient(Ingredient ingredient) {
ingredients.add(ingredient);
}
public void showIngredients() {
for (Ingredient ingredientI : ingredients) {
System.out.println(ingredientI.getIngredientName() + " " + ingredientI.getIngriedientQuantity());
}
}
}

I would personnaly create a "Recipe" Class as follow :
public class Recipe {
private List<Ingredients> ingredients;
+ getters and setters
}
Then change a little bit your ingredient class :
public class Ingredient {
private String ingredientName;
private int ingredientQuantity;
...
}
Then in your main method create a Recipe at the beginning, and then in your while loop create a new instance of Ingredient each time and add it to your recipe.

Related

Exercise With arraylist input with scanner

my exercise is with collect soccer cards inside an arraylist.
inside my code I have to insert the methods: "add, search, remove, print and modify".
From input I must save all data of name of player, surname and country after that from output someone can ask me about player so i can tell it from code.
My problem is i can't add some thing from input and i don't know how to continue with another methods after input with Scanner.
MAIN:
package figurines;
import java.util.*;
public class Figurines {
public ArrayList<Giocatori> lista = new ArrayList<Giocatori>();
public static void main(String[] args) {
System.out.println("1 Penaldo 2 Pessi 3 Neymar 4 Buffon");
Scanner searchBar = new Scanner(System.in);
System.out.println("Inserisci I dati del giocatore");
String search = searchBar.nextLine().toUpperCase();
for (Giocatori liste : lista) {
if (liste.getCognome().equalsIgnoreCase(search)) {
System.out.println(" Nome = " + liste.getNome() +" Paese= " + liste.getPaese());
}
}
}
}
CLASS WHERE I CAN ADD METHODS
package figurines;
import java.util.*;
public class Gestione {
public void input(){
ArrayList<Giocatori> list = new ArrayList<Giocatori>();
Scanner tastiera = new Scanner(System.in);
System.out.println("Inserisci il nome del giocatore: ");
String name;
String surname;
Scanner input = new Scanner(System.in);
System.out.println("Please Enter first name: ");
name = input.nextLine();
System.out.println("Please Enter last name: ");
surname = input.nextLine();
}
}
SOME ARRAY METHODS:
package figurines;
import java.util.*;
public class Giocatori {
private String nome;
private String cognome;
private String paese;
public Giocatori(String nome, String cognome, String paese) {
this.nome = nome;
this.cognome = cognome;
this.paese = paese;
}
public String getNome() {
return nome;
}
public String getCognome() {
return cognome;
}
public String getPaese() {
return paese;
}
}
Well, your classes Gestione and Figurines don't make much sense. Why would you have List of players in your Figurines class? These are basics and you should know, how to make classes and functions.
This is my recommended implementation of Gestione class:
public class Gestione {
private List<Giocatori> list = new ArrayList<>();
public void add(Giocatori giocatori) {
list.add(giocatori);
}
public Giocatori search(String cognome) {
// search by surname
for (Giocatori g : list) {
if (g.getCognome().equals(cognome)) return g;
}
return null;
}
public void remove(Giocatori giocatori) {
list.remove(giocatori);
}
public void print() {
for (Giocatori g : list) {
System.out.println(g);
// create toString method in Giocatori
}
}
public void modify() {
// I don't know what modify should do
}
public List<Giocatori> getList() {
return list;
}
}

how to increment the id and take a lengthy description in java

I have made a Note class where i want to increment the id. It is not getting incremented. And also i am taking input description from console . how to accept a lengthy description like("This is Hello World") in java from the user.Please help.
public class Note {
private String title;
private static int id;
private static int count = 0;
private String description;
public static int getId() {
return id = ++count;
}
public String getTitle() {
id++;
return title;
}
public String getDescription(){
return description;
}
public void setDescription(String description){
this.description=description;
}
public String toString() {
return ("Id : " + id + "\n Title :" + title + "\n Description :"+ description);
}
}
Note Console class that accepts input from the user. It accepts 1. Add Note where in i want to accept a proper description from the user. Second View note where with the help of toString method i print the output. Third is EXIT
import java.util.ArrayList;
import java.util.Scanner;
public class NoteConsole {
public static void NoteConsole() {
final int ADD_NOTE = 1;
final int VIEW_NOTE = 2;
final int EXIT = 3;
boolean loop = false;
NoteConsole nc = new NoteConsole();
Note note = new Note();
ArrayList<Note> notes = new ArrayList<Note>();
NoteServiceSerialize service1 = new NoteServiceSerialize();
System.out.println("Write to the Console 1.AddNote, 2. ToView 3. Exit");
Scanner in = new Scanner(System.in);
int choice = in.nextInt();
while (!loop) {
switch (choice) {
case ADD_NOTE: {
System.out.println("Enter the title");
String title = in.next();
note.setTitle(title);
System.out.println("Enter the description");
String description = in.next();
note.setDescription(description);
notes.add(note);
service1.noteSerialize(notes);
break;
}
case VIEW_NOTE: {
for (Note note1 : notes) {
System.out.println(note1);
}
break;
}
case EXIT: {
//code
}
}
}
}
public static void main(String[] args) {
NoteConsole();
}
}
NoteServiceSerialize class -
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
public class NoteServiceSerialize {
public void noteSerialize (ArrayList<Note> list){
try{
FileOutputStream file = new FileOutputStream("D:\\serializable_notes.txt");
ObjectOutputStream obj = new ObjectOutputStream(file);
obj.writeObject(list);
file.close();
obj.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
Make id instance variable and increase count in constructor of class and assign current value of count to the id
public class Note {
private String title;
private int id;
private static int count = 0;
private String description;
public Note(){
count++;
this.id = count;
}
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription(){
return description;
}
public void setDescription(String description){
this.description=description;
}
public String toString() {
return ("Id : " + id + "\n Title :" + title + "\n Description :"+ description);
}
}
Now every Note object will have separate id.
public class NoteConsole {
//NoteConsole() is not constructor, should avoid same method name and class name
public static void NoteConsole() {
final int ADD_NOTE = 1;
final int VIEW_NOTE = 2;
final int EXIT = 3;
boolean loop = true;
//NoteConsole nc = new NoteConsole();
Note note = new Note();
ArrayList<Note> notes = new ArrayList<Note>();
//NoteServiceSerialize service1 = new NoteServiceSerialize();
Scanner in = new Scanner(System.in);
while (loop) {
System.out.println("Write to the Console 1.AddNote, 2. ToView 3. Exit");
int choice = in.nextInt();
in.nextLine();
switch (choice) {
case ADD_NOTE: {
System.out.println("Enter the title");
//in.nextLine() will read complete line.
String title = in.nextLine();
note.setTitle(title);
System.out.println("Enter the description");
String description = in.nextLine();
note.setDescription(description);
notes.add(note);
//service1.noteSerialize(notes);
break;
}
case VIEW_NOTE: {
for (Note note1 : notes) {
System.out.println(note1);
}
break;
}
case EXIT: {
loop = false;
}
}
}
in.close();
}
public static void main(String[] args) {
NoteConsole();
}
First you should provided the NoteServiceSerialize class too.
for your description problem you should use a in.nextLine() .
and about increment id, doing that in getTitle() is a bad practice.
a better alternative is this way:
private static int lastId;
private int id = nextId();
private static int nextId() {
lastId = ++lastId;
return lastId;
}
and your classes had some other problems too, replace them with this:
public class Note {
private String title;
private String description;
private static int lastId;
private int id = nextId();
private static int nextId() {
lastId = ++lastId;
return lastId;
}
public static int getLastId() {
return lastId;
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public void setTitle(String description) {
this.description = description;
}
#Override
public String toString() {
return ("Id : " + id + "\nTitle :" + title + "\nDescription :" + description);
}
}
import java.util.ArrayList;
import java.util.Scanner;
public class NoteConsole {
final static ArrayList<Note> notes = new ArrayList<Note>();
public static void NoteConsole() {
NoteServiceSerialize service1 = new NoteServiceSerialize();
NoteConsole nc = new NoteConsole();
Note note = new Note();
final int ADD_NOTE = 1;
final int VIEW_NOTE = 2;
final int EXIT = 3;
boolean loop = false;
Scanner in = new Scanner(System.in);
while (!loop) {
System.out.println("Write to the Console 1.AddNote 2. ToView 3. Exit");
int choice = in.nextInt();
switch (choice) {
case ADD_NOTE:
System.out.println("Enter the title :");
String title = in.next();
System.out.println("Enter the description :");
//if you had a problem with description text remove in.next()
in.next();
String description = in.nextLine();
note.setTitle(title);
note.setDescription(description);
notes.add(note);
service1.noteSerialize(notes);
System.out.println("----------------------");
break;
case VIEW_NOTE:
for (Note note1 : notes) {
System.out.println(note1);
System.out.println("----------------------");
}
break;
case EXIT:
loop = !loop;
break;
default:
System.out.println("Not a Valid Option !!!");
}
System.out.println();
}
}
public static void main(String[] args) {
NoteConsole();
}
}
id would remain 0 (default value of primitive) unless your one of the method is called :
public static int getId() {
return id = ++count;
}
public String getTitle() {
id++;
return title;
}
where you actually increment the value of id. Maybe something like :
public String toString() {
return ("Id : " + getId() + "\n Title :" + title + "\n Description :"+ description);
}
Also make sure your count is initialized as :
private static final int count = 0;

How to output an object and its variables

Hi I'm trying to create "a class called HotelReport which, when given a Hotel object will produce a short, textual report describing the name of the hotel, the number of rooms and, for each room, lists the number and size of the beds.", but I'm unsure how to add the rooms and number of beds and get the final report to output, any help?
Hotel Class
import java.util.*;
public class Hotel {
// Hotel Name
private String hotelname;
public void setName(String hotelname) {
this.hotelname = hotelname;
}
public String getName() {
return this.hotelname;
}
// Hotel Rooms
private List<String> hotelRooms = new ArrayList<String>();
public void sethotelRooms(List<String> hotelRooms) {
this.hotelRooms = hotelRooms;
}
public List<String> gethotelRooms() {
return hotelRooms;
}
}
Room Class
import java.util.*;
public class Room {
private int roomNumber;
public Room(int roomNumber) {
this.roomNumber = roomNumber;
}
private static List<Bed> beds = new ArrayList<Bed>();
public Room(List<Bed> beds) {
setBeds(beds);
}
public void setBeds(List<Bed> beds) {
this.beds = beds;
}
public List<Bed> getBeds() {
return beds;
}
public String getFormat() {
return String.format("Beds:\t%s\n", getBeds());
}
}
Bed Class
import java.util.ArrayList;
import java.util.*;
public class Bed {
// size of bed
private int singleBed = 1;
private int doubleBed = 2;
// implement single bed
public int getsingleBed() {
return singleBed;
}
public void setsingleBed() {
this.singleBed = singleBed;
}
// implement double bed
public int getdoubleBed() {
return doubleBed;
}
public void setdoubleBed() {
this.doubleBed = doubleBed;
}
}
HotelReport Class
public class HotelReport {
public static void main(String[] args) {
Hotel hotelRooms = new Hotel();
hotelRooms.setName("Intercontinental");
hotelRooms.addRoom(1,2,3)
}
}
Firstly, you'd better add an addRoom() function in Hotel class like this:
public void addBed(Room room){
this.rooms.add(room);
}
Then, override the toString function for each class above.
#override
public String toString(){
String report = "Hotel name:" + this.hotelName;
return report;
}
Use an ArrayList to hold all the instance of Hotel in your main function, and you can use a loop to retrieve them.
Try this:
Hotel class:
class Hotel {
private String name;
private List<Room> rooms = new ArrayList<>();
public void addRoom(Room room) {
rooms.add(room);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Room> getRooms() {
return rooms;
}
public void setRooms(List<Room> rooms) {
this.rooms = rooms;
}
#Override
public String toString() {
return "Hotel{" +
"name='" + name + '\'' +
", rooms=" + rooms +
'}';
}
}
Room class:
class Room {
private int roomNum;
private List<Bed> beds = new ArrayList<>();
public Room(int roomNum) {
this.roomNum = roomNum;
}
public void addBed(Bed bed) {
beds.add(bed);
}
public int getRoomNum() {
return roomNum;
}
public void setRoomNum(int roomNum) {
this.roomNum = roomNum;
}
public List<Bed> getBeds() {
return beds;
}
public void setBeds(List<Bed> beds) {
this.beds = beds;
}
#Override
public String toString() {
return "Room{" +
"roomNum=" + roomNum +
", beds=" + beds +
'}';
}
}
Bed class
class Bed {
private BedType bedType = BedType.SINGLE;
public Bed() {
}
public Bed(BedType bedType) {
this.bedType = bedType;
}
public BedType getBedType() {
return bedType;
}
public void setBedType(BedType bedType) {
this.bedType = bedType;
}
public enum BedType {
SINGLE, DOUBLE
}
#Override
public String toString() {
return "Bed{" +
"bedType=" + bedType +
'}';
}
}
Finally usage:
public static void main(String[] args) throws Exception {
// beds for room#1
Bed bed1 = new Bed(Bed.BedType.SINGLE);
Bed bed2 = new Bed(Bed.BedType.DOUBLE);
// beds for room#2
Bed bed3 = new Bed(Bed.BedType.SINGLE);
Bed bed4 = new Bed(Bed.BedType.SINGLE);
// Room #1
Room room1 = new Room(1);
room1.addBed(bed1);
room1.addBed(bed2);
// Room #1
Room room2 = new Room(2);
room2.addBed(bed3);
room2.addBed(bed4);
// Hotel
Hotel hotel = new Hotel();
hotel.setName("Intercontinental");
hotel.addRoom(room1);
hotel.addRoom(room2);
}
Get data:
// get the data
String hotelName = hotel.getName();
System.out.println("hotelName = " + hotelName);
List<Room> rooms = hotel.getRooms();
for (Room room : rooms) {
System.out.println("room = " + room);
List<Bed> beds = room.getBeds();
for (Bed bed : beds) {
System.out.println("bed = " + bed);
}
}
Out put:
hotelName = Intercontinental
room = Room{roomNum=1, beds=[Bed{bedType=SINGLE}, Bed{bedType=DOUBLE}]}
bed = Bed{bedType=SINGLE}
bed = Bed{bedType=DOUBLE}
================================
room = Room{roomNum=2, beds=[Bed{bedType=SINGLE}, Bed{bedType=SINGLE}]}
bed = Bed{bedType=SINGLE}
bed = Bed{bedType=SINGLE}
================================
Your code is kind of weird in my opinion. The Hotel class has a field called hotelRooms which is of type ArrayList<String>. Shouldn't it be ArrayList<Room>? That just makes more sense.
And in your Bed class, I am really confused about what you are doing. I think a better implementation would be
public class Bed {
private int bedSize;
//getter and setter for bedSize omitted. I'm lazy
public static final int SIZE_DOUBLE = 2;
public static final int SIZE_SINGLE = 1;
}
You can now set the bed size to double bed like this
yourBed.setBedSize (Bed.SIZE_DOUBLE);
Now that your problems are fixed, let's see how we can turn these objects into String.
To turn an object into a string, you can write a method that returns a String , something like
public String description () {
//blah blah blah
}
However, you better use the toString method in Object for this purpose. Read Effective Java for more info of why you should do this.
#Override
public String toString () {
//blah blah blah
}
And you write a toString method for every class that is related to the hotel. Let's see how the toString methods in each class would look like: (I only show the body cos I'm lazy)
Bed:
if (bedSize == SIZE_DOUBLE)
return "a double bed";
else
return "a single bed";
Room:
return "Room " + Integer.toString (roomNumber);
Hotel:
StringBuilder builder = new StringBuilder ();
builder.append ("A hotel called").append(hotelName).append(".");
builder.append ("It has ").append (hotelRooms.size()).append (" rooms.");
for (Room room : hotelRooms) {
builder.append (room.toString()).append (" has ");
for (Bed bed : room.beds) {
builder.append (bed.toString()).append (" ");
}
builder.append (".");
}
return builder.toString();
Now you can display the hotel's description:
Hotel hotel = new Hotel ();
//do stuff with the hotel, such as setting some of its properties
System.out.println (hotel.toString());

getting elements from an arrayList

I'm having a problem with an arrayList in which I store member objects. I think it might be something to do with the way i've declared it. This is what I have so far
Member Class
package assignment;
import java.util.ArrayList;
public class Member {
private int memberID;
private String memberName;
private int memberAge;
private int numOfBooksLoaned;
private int penalties;
public Member(int memberID, String memberName, int memberAge, int numOfBooksLoaned, int penalties) {
this.memberID = memberID;
this.memberName = memberName;
this.memberAge = memberAge;
this.numOfBooksLoaned = numOfBooksLoaned;
this.penalties = penalties;
}
public int getMemberID() {
return memberID;
}
public void setMemberID(int memberID) {
this.memberID = memberID;
}
public String getMemberName() {
return memberName;
}
public void setMemberName(String memberName) {
this.memberName = memberName;
}
public int getMemberAge() {
return memberAge;
}
public void setMemberAge(int memberAge) {
this.memberAge = memberAge;
}
public int getNumOfBooksLoaned() {
return numOfBooksLoaned;
}
public void setNumOfBooksLoaned(int numOfBooksLoaned) {
this.numOfBooksLoaned = numOfBooksLoaned;
}
public int getPenalties() {
return penalties;
}
public void setPenalties(int penalties) {
this.penalties = penalties;
}
}
MemberList class
package assignment;
import java.util.Scanner;
import java.util.ArrayList;
public class MemberList {
private ArrayList<Member> Members;
public MemberList(ArrayList<Member> Members)
{
this.Members = Members;
}
public void addNewMember()
{
Scanner input = new Scanner(System.in);
boolean successful = false;
int memberID;
String memberName;
int memberAge;
do {
System.out.println("/t/tCreate new member" + "/nPlease enter your full name: ");
memberName = input.nextLine();
for (int i = 0; i < Members.size(); i++) {
if (Members.get(i).getMemberName().equalsIgnoreCase(memberName)) {
System.out.println("This member name is already in use");
} else {
successful = true;
}
}
} while (successful == false);
The problem is just after the for loop in the if statement
if (Members.get(i).getMemberName().equalsIgnoreCase(memberName))
the error says that getMemberName() is undefined for type Member.
Any ideas?
I have used this exact same identical way of using an arrayList and it works fine but it isn't working now for some reason.
try to use a foreach loop in this way
for (Member m : Members) {
if (m.getMemberName().equalsIgnoreCase(memberName)) {
System.out.println("This member name is already in use");
} else {
successful = true;
}
}
Another thing, is discouraged to use Capital letter at first letter in class members in Java, define the list as
private ArrayList<Member> members;

Project will not display search results

I have this project ive been working on all week and cannot get the search in Main.java in the switch case 3 to work. Any idea why this will not display??
Here it all is :(
Main.Java
package hartman;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Printer.printWelcome();
Scanner keyboard = new Scanner(System.in);
ArrayList<Person> personList = new ArrayList<>();
boolean keepRunning = true;
while (keepRunning) {
Printer.printMenu();
Printer.printPrompt("Please enter your operation: ");
String userSelection = keyboard.nextLine();
switch (userSelection) {
case "1":
Database.addPerson(personList);
break;
case "2":
Database.printDatabase(personList);
break;
case "3":
Printer.printSearchPersonTitle();
String searchFor = keyboard.nextLine();
Database.findPerson(searchFor);
Printer.printPersonList(personList);
break;
case "4":
keepRunning = false;
break;
default:
break;
}
}
Printer.printGoodBye();
keyboard.close();
}
}
Database.Java
package hartman;
import java.util.ArrayList;
import java.util.Scanner;
public class Database {
static Scanner keyboard = new Scanner(System.in);
private static ArrayList<Person> personList = new ArrayList<Person>();
public Database() {
}
public static void addPerson(ArrayList<Person> personList) {
Printer.printAddPersonTitle();
Printer.printPrompt(" Enter first name: ");
String addFirstName = keyboard.nextLine();
Printer.printPrompt(" Enter last Name: ");
String addLastName = keyboard.nextLine();
Printer.printPrompt(" Enter social Security Number: ");
String addSocial = keyboard.nextLine();
Printer.printPrompt(" Enter year of birth: ");
int addYearBorn = Integer.parseInt(keyboard.nextLine());
System.out.printf("\n%s, %s saved!\n", addFirstName, addLastName);
Person person = new Person();
person.setFirstName(addFirstName);
person.setLastName(addLastName);
person.setSocialSecurityNumber(addSocial);
person.setYearBorn(addYearBorn);
personList.add(person);
}
public static void printDatabase(ArrayList<Person> personList) {
System.out
.printf("\nLast Name First Name Social Security Number Age\n");
System.out
.printf("=================== =================== ====================== ===\n");
for (Person p : personList) {
System.out.printf("%-20s%-21s%-24s%s\n", p.getLastName(),
p.getLastName(), p.getSocialSecurityNumber(), p.getAge());
}
}
public static ArrayList<Person> findPerson(String searchFor) {
ArrayList<Person> matches = new ArrayList<>();
for (Person p : personList) {
boolean isAMatch = false;
if (p.getFirstName().equalsIgnoreCase(searchFor)) {
isAMatch = true;
} else if (p.getLastName().equalsIgnoreCase(searchFor)) {
isAMatch = true;
} else if (p.getSocialSecurityNumber().contains(searchFor)) {
isAMatch = true;
;
} else if (String.format("%d", p.getAge()).equals(searchFor)) {
isAMatch = true;
}
if (isAMatch) {
matches.add(p);
}
Printer.printPersonList(matches);
}
return matches;
}
}
Person.Java
package hartman;
public class Person {
private String firstName;
private String lastName;
private String socialSecurityNumber;
private int yearBorn;
public Person() {
}
public Person(String firstName, String lastName,
String socialSecurityNumber, int yearBorn) {
this.firstName = firstName;
this.lastName = lastName;
this.socialSecurityNumber = socialSecurityNumber;
this.yearBorn = yearBorn;
}
public int getAge() {
return yearBorn = 2014 - yearBorn;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getSocialSecurityNumber() {
return socialSecurityNumber;
}
public void setSocialSecurityNumber(String socialSecurityNumber) {
this.socialSecurityNumber = socialSecurityNumber;
}
public int getYearBorn() {
return yearBorn;
}
public void setYearBorn(int yearBorn) {
this.yearBorn = yearBorn;
}
}
Printer.Java
package hartman;
import java.util.ArrayList;
public class Printer {
public static void printWelcome() {
System.out.printf("WELCOME TO PERSON DATABASE!\n");
}
public static void printGoodBye() {
System.out.printf("\nGOOD BYE!!\n");
}
public static void printMenu() {
System.out.printf("\nMain Menu\n");
System.out.printf("---------\n\n");
System.out.printf(" 1. Add a new Person to the database.\n");
System.out.printf(" 2. Print the database.\n");
System.out.printf(" 3. Search for a person in the database.\n");
System.out.printf(" 4. Exit the application.\n");
System.out.printf("\n");
}
public static void printPrintMenu() {
System.out.printf("Print\n\n");
}
public static void printAddPersonTitle() {
System.out.printf("\nAdd Person to Database\n\n");
}
public static void printPrompt(String promptForWhat) {
System.out.printf("%s", promptForWhat);
}
public static void printPersonSaved(Person personSaved) {
System.out.printf("%s", personSaved);
}
public static void printSearchPersonTitle() {
System.out.printf("\nSearch for Person in Database\n\n");
System.out.printf("Enter search value: ");
}
public static void printPersonList(ArrayList<Person> personListToPrint) {
System.out
.printf("\nLast Name First Name Social Security Number Age\n");
System.out
.printf("=================== =================== ====================== ===\n");
for (Person p : personListToPrint) {
System.out.printf("%-20s%-21s%-24s%s\n", p.getLastName(),
p.getLastName(), p.getSocialSecurityNumber(), p.getAge());
}
}
}
Any help would be great... im about to break my pc and give up.
The problems is that you are using the static instance from DataBase
ArrayList<Person> personList = new ArrayList<Person>();
I was gonna say follow the rules of OOP click here if you want to learn
But since you already started a lot of coding ill try to answer your problem..
Dont use instance of personList in the DataBase. Just use from the Main class.
here is where the problem started:
for (Person p : personList)
You are using an empty ArrayList from DataBase class..
The one that has data and you are using is from the Main class..
solution:
Remove the
private static ArrayList<Person> personList = new ArrayList<Person>();
from your DataBase then do this in you Main Class
public class Main {
public static ArrayList<Person> personList;
public static void main(String[] args) {
Printer.printWelcome();
Scanner keyboard = new Scanner(System.in);
personList = new ArrayList<Person>();
and change the for loop to:
for (Person p : Main.personList)
This is what you get when you dont use OOP on your problems its soo ugly and complicated..
Its better when it is object oriented.. P.S. learn that..

Categories

Resources