I am making a Hospital Management system project in Java.
I have 3 classes.
One class has the main method, the other class is the Hospital class which has methods printing out the details of the hospital and another method printing out the staff of the hospital.
The third class is the HospitalStaff class which has a toString method for all details of the Staff, and an addStaff method. The staff are added in an arraylist.
i want the method that prints all the staff to exist in the Hospital class how do I do that?
Here is my code:
import java.util.ArrayList;
import java.util.List;
public class HospitalProject {
public static void main(String[] args) {
Hospital h = new Hospital();
h.Hospitalinformation();
HospitalStaff hs = new HospitalStaff();
hs.addHospitalStaff("A103", "Name1", "Lastname1", "Surgery", "Doctor");
hs.addHospitalStaff("A124", "Name2", "Lastname2", "Surgery", "Doctor");
}
}
/* This is the Hospital class. It has 3 methods. The HospitalInformation method prints the name and the address, name, email address and phone number of the hospital.
* It declares and array list by the name of listofStaff of the type HospitalStaff.
* It consists of a seeStaff method which is supposed to show all staff working at the hospital.
*/
class Hospital{
public String name = "Red Cross";
public String Address = "whatever";
public String phonenum = "whatever2";
private String email = "whatever#gmail.com";
public void Hospitalinformation() {
System.out.println("The name of the hospital is: " +name + " \nThe name of the Address: " + Address + "\nPhone number: "+phonenum + " \nEmail Address: " + email);
}
public void seeStaff() {
HospitalStaff hs1 = new HospitalStaff();
for(String stafflist: hs1.listofStaff) {
System.out.println(stafflist);
}
}
}
/*The Hospital Staff method consists of toString method as well as a addHospitalStaff method.
* The seeStaff method is added for debugging purposes, it is however, supposed to exist in the Hospital method.
*/
class HospitalStaff {
private String StaffId;
public String firstname;
public String lastname;
public String department;
public String stafftype;
List<String>listofStaff = new ArrayList<String>();
public void addHospitalStaff(String StaffId, String firstname, String lastname, String department, String stafftype) {
String here = StafftoString(StaffId, firstname, lastname, department, stafftype);
listofStaff.add(here);
}
public String StafftoString(String StaffId, String firstname, String lastname, String department, String stafftype) {
return String.valueOf(firstname) + " " + String.valueOf(lastname) +" " + String.valueOf(StaffId) +" " + String.valueOf(department) +" " + String.valueOf(stafftype);
}
public void seeStaff() {
for(String stafflist: listofStaff) {
System.out.println(stafflist);
}
}
}
I tried creating a method called seeStaff() in the Hospital class and created an HospitalStaff object by the name of "hs1" in that method.
I then used the HospitalStaff object to call the arraylist (which was called listofStaff) that was created in the HospitalStaff class. I used it in the for each loop as (String stafflist : hs1.listofStaff).
However, when i create a Hospital class object in the main and call the seeStaff() method, it does not print anything. I am not sure why that happens.
Inside your seeStaff method, you are creating a new instance of HospitalStaff, which when created has no staff members in it. Because of this, when you iterate over the list of staff members in that empty instance, you get no output. You create another instance of HospitalStaff in your main() but you don't do anything with that instance.
One way to fix this would be to create your HospitalStaff instance first. Then, when you create your Hospital instance, pass the HospitalStaff instance into the constructor for Hospital so that it can be stored in the instance. Then your showStaff method can print the values in your HospitalStaff instance. Here's what that looks like:
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
// Create an object containing the hospital's staff
HospitalStaff hs = new HospitalStaff();
hs.addHospitalStaff("A103", "Name1", "Lastname1", "Surgery", "Doctor");
hs.addHospitalStaff("A124", "Name2", "Lastname2", "Surgery", "Doctor");
// Create a Hospital object, passing it the `HospitalStaff` instance containing the hospital's staff.
Hospital h = new Hospital(hs);
h.Hospitalinformation();
h.seeStaff(); // <- Print a list of hospital staff members
}
}
/* This is the Hospital class. It has 3 methods. The HospitalInformation method prints the name and the address, name, email address and phone number of the hospital.
* It declares and array list by the name of listofStaff of the type HospitalStaff.
* It consists of a seeStaff method which is supposed to show all staff working at the hospital.
*/
class Hospital{
public String name = "Red Cross";
public String Address = "whatever";
public String phonenum = "whatever2";
private String email = "whatever#gmail.com";
private HospitalStaff hs;
public Hospital(HospitalStaff hs) {
this.hs = hs; // <- Associate the passed in HospitalStaff instance with this `Hospital` instance.
}
public void Hospitalinformation() {
System.out.println("The name of the hospital is: " +name + " \nThe name of the Address: " + Address + "\nPhone number: "+phonenum + " \nEmail Address: " + email);
}
// Print the members of the hospital's staff
public void seeStaff() {
for(String stafflist: hs.listofStaff) {
System.out.println(stafflist);
}
}
}
/*The Hospital Staff method consists of toString method as well as a addHospitalStaff method.
* The seeStaff method is added for debugging purposes, it is however, supposed to exist in the Hospital method.
*/
class HospitalStaff {
private String StaffId;
public String firstname;
public String lastname;
public String department;
public String stafftype;
List<String>listofStaff = new ArrayList<String>();
public void addHospitalStaff(String StaffId, String firstname, String lastname, String department, String stafftype) {
String here = StafftoString(StaffId, firstname, lastname, department, stafftype);
listofStaff.add(here);
}
public String StafftoString(String StaffId, String firstname, String lastname, String department, String stafftype) {
return String.valueOf(firstname) + " " + String.valueOf(lastname) +" " + String.valueOf(StaffId) +" " + String.valueOf(department) +" " + String.valueOf(stafftype);
}
public void seeStaff() {
for(String stafflist: listofStaff) {
System.out.println(stafflist);
}
}
}
Result:
The name of the hospital is: Red Cross
The name of the Address: whatever
Phone number: whatever2
Email Address: whatever#gmail.com
Name1 Lastname1 A103 Surgery Doctor
Name2 Lastname2 A124 Surgery Doctor
Related
I'm an inexperienced developer that is learning Java.
I'm working on this AddressBook, where I'm implementing AspectJ to one of my functions (Update Contact).
Before updating the contact, obviously the user needs to add a Contact, and my saveContact code looks like this:
public class Contacts { //class to manage the contacts information
public String name;
public String street;
public String city;
public String state;
public int zip;
public long phoneNumber;
public Scanner input;
public void saveContact()
{//code to add and save a contact to the book
input = new Scanner(System.in);
System.out.println("Plase enter contact Name and Lastname: ");
name = input.nextLine();
System.out.println("\nPlase enter Street of contact: ");
street = input.nextLine();
System.out.println("\nPlase enter City of the contact: ");
city = input.nextLine();
System.out.println("\nPlase enter State of the contact: ");
state = input.nextLine();
System.out.println("\nPlase enter the Zipcode of the contact: ");
zip = input.nextInt();
System.out.println("\nPlase enter the contact Phone number (Ex 1115550000): ");
phoneNumber = input.nextLong();
System.out.println("Done! Contact Saved");
}
I have more options like Update Contact, Find Contact and Delete Contac. before the Update Contact function executes, I want to run an Aspect that saves the values that the user entered to the variables(name, city, state, etc) in a file.txt, before assigning the new values in the Update Contact code.
My issue is that when the Aspect advise executes, my .txt file comes with null instead of the values assigned by the user in the Add Contact code.
My Aspect looks like this:
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public aspect AspectUpdateContact { //code to save the old information of the contact to the file before updating the contact
pointcut aspectCallUpdateFile() : call (void updateContact()) && within (Menu);
before() : aspectCallUpdateFile()
{
/*******Code is running and saving to the file but not bringing the values of the variables, saving null values*/
Contacts ct = new Contacts();
try {
PrintWriter pwrite = new PrintWriter(new FileWriter("UpdatesLog.txt", true));//to append the write to the end of the file
pwrite.println("Record Updated->" + ct.name +":"+ ct.street +":"+ ct.city +":"+ ct.state +":"+ ct.zip +":"+ ct.phoneNumber);
pwrite.close();//close the Print Writer
}
catch (IOException e) {
System.out.println(e.getMessage());
}
}// end of code for pointcut
}//end of aspect
My final output in the txt file is: Record Updated:null:null:null:null:0:0
I refactored your code a bit (no more plural in class name, renamed methods, private fields, toString() method, convenience constructor, try with resources in aspect) and also fixed the aspect by using target() with argument binding in the aspect:
Contact data class:
package de.scrum_master.app;
import java.util.Scanner;
public class Contact {
private String name;
private String street;
private String city;
private String state;
private int zip;
private long phoneNumber;
private Scanner input;
public Contact() {}
public Contact(String name, String street, String city, String state, int zip, long phoneNumber) {
this.name = name;
this.street = street;
this.city = city;
this.state = state;
this.zip = zip;
this.phoneNumber = phoneNumber;
}
#Override
public String toString() {
return "Contact[name=" + name + ", street=" + street + ", city=" + city + ", state=" + state +
", zip=" + zip + ", phoneNumber=" + phoneNumber + "]";
}
public void updateContact() {
input = new Scanner(System.in);
System.out.println("Please enter contact Name and Lastname: ");
name = input.nextLine();
System.out.println("\nPlease enter Street of contact: ");
street = input.nextLine();
System.out.println("\nPlease enter City of the contact: ");
city = input.nextLine();
System.out.println("\nPlease enter State of the contact: ");
state = input.nextLine();
System.out.println("\nPlease enter the Zipcode of the contact: ");
zip = input.nextInt();
System.out.println("\nPlease enter the contact Phone number (Ex 1115550000): ");
phoneNumber = input.nextLong();
System.out.println("Done! Contact updated.\n");
}
}
Dummy menu class with main method:
package de.scrum_master.app;
public class Menu {
public void updateContact(Contact contact) {
contact.updateContact();
}
public static void main(String[] args) {
Menu menu = new Menu();
Contact contact = new Contact("Albert Einstein", "101 Main St", "Middle of Nowhere", "Utah", 12345, 11223344);
menu.updateContact(contact);
menu.updateContact(contact);
}
}
As you can see, I am creating an initial contact object and then update it twice in order to create two lines of log output.
Logging aspect:
package de.scrum_master.aspect;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import de.scrum_master.app.Contact;
import de.scrum_master.app.Menu;
public aspect UpdateContactAspect {
pointcut callUpdateContact(Contact contact) :
call(void updateContact()) && within(Menu) && target(contact);
before(Contact contact) : callUpdateContact(contact) {
try (PrintWriter writer = new PrintWriter(new FileWriter("UpdatesLog.txt", true))) {
writer.println("Record updated -> " + contact);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Console log for sample run:
Please enter contact Name and Lastname:
John Doe
Please enter Street of contact:
321 Broadway
Please enter City of the contact:
New York City
Please enter State of the contact:
New York
Please enter the Zipcode of the contact:
54321
Please enter the contact Phone number (Ex 1115550000):
0123456789
Done! Contact updated.
Please enter contact Name and Lastname:
Donald Duck
Please enter Street of contact:
33 Wherever
Please enter City of the contact:
Quacktown
Please enter State of the contact:
Duckstate
Please enter the Zipcode of the contact:
88099
Please enter the contact Phone number (Ex 1115550000):
999333111
Done! Contact updated.
Log file content after sample run:
Record updated -> Contact[name=Albert Einstein, street=101 Main St, city=Middle of Nowhere, state=Utah, zip=12345, phoneNumber=11223344]
Record updated -> Contact[name=John Doe, street=321 Broadway, city=New York City, state=New York, zip=54321, phoneNumber=123456789]
There are more things which need refactoring, but I am stopping here.
edit - Here I gave a specific obj. as an example but I'm asking for any obj. I am given *
I'm looking for a way to get all public attributes in the class and all subclasses of an object (name of the attribute and its value).
Let say we have a People object:
i
mport java.util.ArrayList;
public class People {
public ArrayList<Person> ppl= new ArrayList<Person>();
int count=2;
public People() {
ppl.add(new Person(55, "Daddy", "Long Legs"));
ppl.add(new Person(20, "Jhon", "Snow"));
}
public class Person{
public int age;
public Name name;
public Person(int age, String first, String last){
this.name = new Name(first, last);
this.age = age;
}
public class Name{
String first;
String last;
public Name(String first, String last) {
this.first = first;
this.last = last;
}
}
}
}
I saw a reference here (I can't comment on there bc I don't have enough points):
Java reflection get sub class variable values / get object instance from member field
and tried to implement it also but then my output is
ppl [People$Person#4aa298b7, People$Person#7d4991ad]
whereas I need it needs to go into each Person and extract its variables(and their values). I searched for a information that could help me but I couldn't find anything..any advice?
public People() {
ppl.add(new Person(55, "Daddy", "Long Legs"));
ppl.add(new Person(20, "Jhon", "Snow"));
for (Person person : ppl) {
System.out.println(person.name.last);
System.out.println(person.name.first);
System.out.println(person.age);
}
System.out.println("Size of list: " + ppl.size());
}
Example without toString() method.
I Agree with #Jordi Castilla , you need to override toString method properly to get correct output.
For Example :
import java.util.ArrayList;
class People {
public ArrayList<Person> ppl= new ArrayList<Person>();
int count=2;
public People() {
ppl.add(new Person(55, "Daddy", "Long Legs"));
ppl.add(new Person(20, "Jhon", "Snow"));
}
#Override
public String toString() {
return "{ Count: "+this.count + " , People:" + this.ppl+" }";
}
public class Person{
public int age;
public Name name;
public Person(int age, String first, String last){
this.name = new Name(first, last);
this.age = age;
}
#Override
public String toString() {
return "{ Name: "+this.name + " , Age:" + this.age+" }";
}
public class Name{
String first;
String last;
public Name(String first, String last) {
this.first = first;
this.last = last;
}
#Override
public String toString() {
return "{ FirstName: "+this.first + ", LastName: " + this.last+ " }";
}
}
}
public static void main(String[] args) {
People ppl = new People();
System.out.println("OUTPUT => "+ ppl.toString());
}
}
//Output
OUTPUT => {
Count: 2 ,
People:[
{ Name: { FirstName: Daddy, LastName: Long Legs } , Age:55 },
{ Name: { FirstName: Jhon, LastName: Snow } , Age:20 }
]
}
I believe the closest you can get is related to this question java: get all variable names in a class .
Using Field[] fields = YourClassName.class.getFields(); returns all class fields as java.lang.reflect.Field.
You can check if field is public using Field.getModifiers() and Modifier.isPublic(Modifier).
You can get the field value using Object Field.get().
Hope that helps.
code a toString() method
What you are getting People$Person#4aa298b7 is the Object.toString representation....
getClass().getName() + '#' + Integer.toHexString(hashCode())
IMHO You need to override the toString() method in both classes: Person and Name.
For example:
public class Name{
String first;
String last;
public Name(String first, String last) {
this.first = first;
this.last = last;
}
#Override
public String toString() {
return this.first + " " + this.last;
}
}
get fields and values based on known Person class
If this does not fit, you can get fields names and values using reflection like this:
public static void main(String[] args) throws IllegalAccessException
{
People pe = new People();
Field[] allFields = People.Person.class.getDeclaredFields();
for (Field field : allFields)
{
for (People.Person p : pe.ppl)
System.out.println("Name: " + field.getName() + ". Value: " + field.get(p));
}
}
OUTPUT:
Name: age. Value: 55
Name: age. Value: 20
Name: name. Value: Daddy Long Legs
Name: name. Value: Jhon Snow
Name: this$0. Value: People#677327b6
Name: this$0. Value: People#677327b6
NOTE: if you don't want this 2 final values representing the People with ugly results you can:
Split Person and Name and make them 2 independent classes
Make a toString() method in People class
dynamically get fields from inner classes
If you want to dynamically get fields from inner classes:
public static void main(String[] args) throws IllegalAccessException
{
Class[] allClasses = People.class.getClasses();
for (Class clazz : allClasses) {
Field[] allFields = clazz.getFields();
for (Field field : allFields) {
String className = clazz.getName();
String fieldName = field.getName();
System.out.println("Class name: " + className + " - Field name: " + fieldName + ".");
}
}
}
OUTPUT:
Class name: People$Name - Field name: first.
Class name: People$Name - Field name: last.
Class name: People$Person - Field name: age.
Class name: People$Person - Field name: name.
But not sure how you can get values from inside the ArrayList<Person>....
here is a recursive method I did (after I added a toString method to Name class). Here it is. However, it is still doesn't prints the variable names inside the ppl list:
private static String getAllFields(Object obj){
Class<?> objClass = obj.getClass();
StringBuilder res = new StringBuilder();
Field[] fields = objClass.getFields();
res.append(objClass+"\n");
for(Field field : fields) {
Class<?> type = field.getType();
String name = field.getName();
res.append(" name: "+name+ " ");
try {
Object value = field.get(obj);
res.append("value: "+value+ "\n");
if (!type.isPrimitive() && !name.contains("java.lang"))
{
res.append(getAllFields(value));
}
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
}
return res.toString();
}
here is the output:
class People
name: ppl value: [Daddy Long Legs 55 , Jhon Snow 20 ]
class java.util.ArrayList
name: count value: 2
notice that there isn't the Person class name there in the output or the names of the variable names of the variables there. I don't really understand why
Consider Person and Address classes as:
class Person {
String name;
int age;
Address first;
Address second;
}
class Address {
String country;
String city;
}
I want to parse csv file to Person objects. sample csv file is:
NAME,AGE,COUNTERY_1,CITY_1,COUNTRY_2,CITY_2
john,50,USA,Arizona,UK,London
bob,27,France,paris,USA,Felorida
I write a model method:
CsvSchema bootstrapSchema = CsvSchema.emptySchema().withHeader();
CsvMapper mapper = new CsvMapper();
MappingIterator<Person> readValues = mapper
.readerWithTypedSchemaFor(Person.class)
.with(bootstrapSchema)
.readValues(file);
return readValues.readAll();
How to add Address class mapping to mapper?
You can't really do this with Jackson, but univocity-parsers can with its #Nested annotation:
First define your Address class like this:
public static class Address {
#Parsed
String country;
#Parsed
String city;
#Override
public String toString() {
return "Address{country='" + country + '\'' + ", city='" + city + '\'' + '}';
}
}
Now if you look at your input, we need to somehow associate the headers "country_1" and "city_1" with the fields in your Address class. This is done using a custom HeaderTransformer class that appends the index to the header name. Let's define it like this:
public static class SuffixAppender extends HeaderTransformer {
private String suffix;
public SuffixAppender(String... args) {
suffix = args[0];
}
#Override
public String transformName(Field field, String name) {
return name + "_" + suffix;
}
}
Now you can define your Person class with nested Address attributes:
public static class Person {
#Parsed
String name;
#Parsed
int age;
#Nested(headerTransformer = SuffixAppender.class, args = "1")
Address first;
#Nested(headerTransformer = SuffixAppender.class, args = "2")
Address second;
#Override
public String toString() {
return "Person{name='" + name + '\'' + ", age=" + age + ", first=" + first + ", second=" + second + '}';
}
}
The above instructs the parser to get the field names in Address and append the given suffix to it with your SuffixAppender. The result will be matched against the headers of your input.
Finally you are ready to parse. There are many ways to use the parser, but the simplest is:
String input = "" +
"NAME,AGE,COUNTRY_1,CITY_1,COUNTRY_2,CITY_2\n" +
"john,50,USA,Arizona,UK,London\n" +
"bob,27,France,paris,USA,Florida";
CsvParserSettings settings = new CsvParserSettings(); //configure the parser
settings.detectFormatAutomatically(); //detects line separators and delimiters
//parse the input with the settings above, into a list of Person objects
List<Person> personList = new CsvRoutines(settings).parseAll(Person.class, new StringReader(input));
Let's see the result with:
Person person1 = personList.get(0);
Person person2 = personList.get(1);
System.out.println(person1);
System.out.println(person2);
Output:
Person{name='john', age=50, first=Address{country='USA', city='Arizona'}, second=Address{country='UK', city='London'}}
Person{name='bob', age=27, first=Address{country='France', city='paris'}, second=Address{country='USA', city='Florida'}}
Hope it helps.
Disclaimer: I'm the author of this library. It's open source and free (Apache 2.0 license)
I have three classes:
Human
Father
Child.
Child class extends Father and Father extends Human.
I have created some instances of each class and stored them into a ArrayList.
Now I want to write a method to check if object father1 has the same field address(for example: "21 str Goodwin") as the Object child1 address field (instances of class Father and Child) and give this method to my ArrayList and print if any results was found.
How can I do this?
Let me add my code here for more clarity:
Human class:
public class Om {
String nume;
String prenume;
String cnp;
Om(String nume,String prenume,String cnp){
this.nume=nume;
this.prenume=prenume;
this.cnp=cnp;
}
#Override
public String toString() {
return "Numele omului: " + this.nume +"\n"+ "Prenumele omului: " + this.prenume +"\n"+ "Cnp-ul omului: " + this.cnp + "\n" ;
}
}
Father class:
public class Parinte extends Om{
String domiciliu;
Parinte(String nume, String prenume, String cnp, String domiciliu){
super(nume,prenume,cnp);
this.domiciliu=domiciliu;
}
#Override
public String toString() {
return "Numele parintelui: " + nume +"\n"+
"Prenumele parintelui :" + prenume +"\n"+
"Cnp-ul parintelui: " + cnp +"\n"+
"Domiciliul parintelui: "+domiciliu+"\n";
}
}
Child class:
public class Copil extends Parinte {
int varsta;
Copil(String nume, String prenume, String cnp, String domiciliu, int varsta){
super(nume,prenume,cnp,domiciliu);
this.varsta=varsta;
}
#Override
public String toString() {
return "Numele copilului: " + nume +"\n"+
"Prenumele copilului :" + prenume +"\n"+
"Cnp-ul copilului: " + cnp +"\n"+
"Domiciliul compiluiui: "+ domiciliu +"\n"+
"Varsta copilului: "+varsta+"\n";
}
}
My method to sort list alphabetical:
import java.util.*;
public class comparareNume implements Comparator<Om>{
public int compare(Om om1, Om om2){
return om1.nume.compareTo(om2.nume);}
}
And my main class:
import java.util.*;
public class main {
public static void main(String[] args) {
Om om1=new Om("Dubolari", "Dragos", "2006004034120");
Om om2=new Om("Andronachi","Andrei", "12591295967123");
Parinte p1=new Parinte("Vreascu","Andy","5845289564684","Al. Cel Bun 13");
Copil c1 = new Copil("Mamaliga","George","5942356874156","Al. Cel Bun 13", 15);
List<Om> colectie = new ArrayList<Om>();
colectie.add(om1);
colectie.add(p1);
colectie.add(c1);
colectie.add(om2);
comparareNume comparNume = new comparareNume();
Collections.sort(colectie, comparNume);
System.out.println(colectie);
}
}
FatherObj.getAddress().equals(ChildObj.getAddress())
Example for getAddress() and field address inside of Child and Father
private String address = "21 str Goodwin"
public String getAddress() {
return address;
}
Put a function like this into Human, which is set via the constructor (it could also be set via a setter, but doing so in the constructor allows for immutability).
public Human(String address) {
addr = address;
}
public String getAddress() {
return addr;
}
This function is accessible to all sub-classes.
Then you can access it as suggested by #NappaTheSaiyan
I am trying to create an application that will let you
1 - add people to a small database
2 - append their name onto an array
3 - when retrieving information previously entered, the array will be used to select the person
4 - retrieve unique information of the person selected
I have two classes, Person(), which is supposed to construct a new person with the given variables and store that information for reading later, and PeopleManager().
Person class:
public class Person extends Object
{
private static int theNumPersons = 0; // initialize num
private String itsFirstName;
private String itsLastName;
private int itsBirthYear;
public Person (String first, String last, int year)
{
super();
theNumPersons++; // update num
itsFirstName = first;
itsLastName = last; // initialize last name
itsBirthYear = year;
}
/** Tell how many different Persons exist. */
public static int getNumPersons() // access num
{
return theNumPersons;
}
/** Return the birth year. */
public int getBirthYear()
{
return itsBirthYear;
}
/** Return the first name. */
public String getFirstName()
{
return itsFirstName;
}
/** Return the last name. */
public String getLastName() // access last name
{
return itsLastName;
}
/** Replace the last name by the specified value. */
public void setLastName (String name) // update last name
{
itsLastName = name;
}
}
PeopleManager class:
import java.util.*;
import javax.swing.*;
public class PeopleManager
{
static ArrayList names = new ArrayList();
static int selection;
public static void main()
{
askSelection();
}
public static void askSelection()
{
Object[] options = { "Add to Database", "Retrieve Info" };
selection = JOptionPane.showOptionDialog(null, "What would you like to do?", "People Database Application", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
executeSelection();
}
public static void executeSelection()
{
if (selection == 0)
{
addPerson();
askSelection();
}
if (selection == 1)
{
Object[] nameArray = names.toArray();
Object person = JOptionPane.showInputDialog(null, "Select person to grab info from.", "People Database Application", JOptionPane.DEFAULT_OPTION, null, nameArray, nameArray[0]);
getInfo(person);
askSelection();
}
}
public static void addPerson()
{
String newFirst = JOptionPane.showInputDialog (null, "Enter the first name.", "John");
String newLast = JOptionPane.showInputDialog (null, "Enter the last name.", "Doe");
String sNewYear = JOptionPane.showInputDialog (null, "Enter that person's birth year.", "1965");
String newFullName = (newFirst + " " + newLast);
int iNewYear = Integer.parseInt(sNewYear);
names.add(newFullName);
Person newFullName = new Person (newFirst, newLast, iNewYear);
JOptionPane.showMessageDialog (null, "Person successfully added.");
}
public static void getInfo(Object p)
{
String infoFirst = p.getFirstName;
String infoLast = p.getLastName;
String infoYear = p.getBirthYear;
String databaseSize = getNumPersons();
JOptionPane.showMessageDialog(null, "First Name: " + infoFirst + "\nLast Name: " + infoLast + "\nBirth Year: " + infoYear + "\n\nTotal people in database: " + databaseSize);
}
}
I know I'm not doing something right, and I'm pretty sure it has to do with the way I tried to make a new Person() by using a variable. The problem is, if I can't use a variable to make a new Person(), how can I give the stats to the application user that is specific to the person they entered in?
You are creating a new Person object
names.add(newFullName);
Person newFullName = new Person (newFirst, newLast, iNewYear);
but you are not keeping that referenced (by adding it array or something) but you have names array that keep track of the names. Also, you should rename the variable to something else because you have 2 variable named the same.
EDIT:
As you asked, here is a simple example.
class1:
public class Person
{
public String name;
public String lastname;
public Person(String name, String lastname)
{
this.name = name;
this.lastname = lastname;
}
public String toString()
{
return this.name + " " + this.lastname;
}
}
class 2:
import java.util.*;
public class PersonManager{
//array list to keep track of all the Person objects that will be created
public static ArrayList<Person>peoples = new ArrayList<Person>();
//assume this function takes input from user and returns a new
//person object
public static Person getPerson(String name, String last)
{
Person p = new Person(name, last);
return p;
}
//this function removes a person with the first name
public static boolean removePerson(String name)
{
//we should loop through the array and find the object we want to delete
Person objectToRemove = null;
for (Person p : peoples)
{
if (p.name.equals(name))
{
//this is the object we want to remove
//because the name matched
objectToRemove = p;
break;
}
}
//we will actually remove the object outside of the loop
//so we don't run into errors...
if (objectToRemove != null)
{
//tell array list to remove the object we wanted to delete
peoples.remove(objectToRemove);
System.out.println("\nRemoving person = "+objectToRemove);
}
return objectToRemove != null;
}
public static void printInfo()
{
System.out.println("\n\nPrinting info");
//loop through all the object in the peoples array and print out their names
for (Person p : peoples)
{
System.out.println(p);
}
System.out.println("In total, there are "+ peoples.size() +" objects saved in the array");
}
public static void main(String []args)
{
//creating 3 different people and adding them to the array list
peoples.add(getPerson("John", "Doe"));
peoples.add(getPerson("Jane", "Doe"));
peoples.add(getPerson("Will", "Smith"));
//print all the users in the array and the size of the array
printInfo();
//remove the person with first name = John.
removePerson("John");
//print all the users in the array and the size of the array
printInfo();
}
}
String newFullName = (newFirst + " " + newLast);
Person newFullName = new Person (newFirst, newLast, iNewYear);
you are saying newFullName is String and Person, this is impossible
also, you have to change the last function to this:
public static void getInfo(Person p)
{
String infoFirst = p.getFirstName();
String infoLast = p.getLastName();
String infoYear = Integer.toString(p.getBirthYear());
String databaseSize = Integer.toString(Person.getNumPersons());
...
}