getting NULL in setter and getter - JAVA - java

i always end up with this error "Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException" when im running my program. i have Member Class where i code my setter and getter. All the entities i need id there. now i have another method in "Admin Class"
public class Admin {
private ArrayList<Member> members;
private String AccessName;
private String username;
private String password;
public Admin(){
this.AccessName="Ms. April Santos";
this.username = "estella";
this.password = "teller";
this.members = new ArrayList<Member>();
}
public ArrayList<Member> getMembers() {
return members;
}
public void setMembers(ArrayList<Member> members) {
this.members = members;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getAccessName() {
return AccessName;
}
public void setAccessName(String AccessName) {
this.AccessName=AccessName;;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Admin other = (Admin) obj;
if ((this.username == null) ? (other.username != null) : !this.username.equals(other.username)) {
return false;
}
return true;
}
#Override
public int hashCode() {
int hash = 7;
hash = 97 * hash + (this.username != null ? this.username.hashCode() : 0);
return hash;
}
#Override
public String toString() {
return "Admin{" + "members=" + members + ", AccessName;=" + AccessName + ", username=" + username + ", password=" + password + '}';
}
public Member searchMember(Member member){
return this.searchMember(member.getMemberId());
}
public Member searchMember(String memberId){
for(Member member : this.members){
if(member.getMemberId().equals(memberId)){
return member;
}
}
return null;
}
public Member addMember(Member member){
if (this.searchMember(member) == null){
this.members.add(member);
return member;
}
return null;
}
public Member addMember(String memberId, String firstName,String middleName, String lastName){
if (this.searchMember(memberId) == null){
Member member = new Member(memberId, firstName,middleName, lastName);
this.members.add(member);
return member;
}
return null;
}
public boolean validateLogin(String username, String password){
boolean valid = false;
valid = this.username.equals(username) && this.password.equals(password);
return valid;
}
}
now im calling public addMember(String memberId, String firstName,String middleName, String lastName) in my AddMemberView(GUI). im trying to get all the text in the textfield/combobox and set it so that it will be temporary saved and ready to be saved in database as i code my DAO. this is my AddMemberView btnSave action look:
import java.sql.SQLException;
import java.text.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import rtu.tomis.bom.Admin;
import rtu.tomis.bom.Member;
import rtu.tomis.dao.MemberDao;
public class AddMemberView extends javax.swing.JPanel {
private MainFrameView mainFrameView;
private Member member;
private Admin admin;
AddMemberView(Member memb, Admin admin){
this.member= memb;
this.admin= admin;
}
public AddMemberView() {
initComponents();
}
public AddMemberView(MainFrameView mf) {
this.mainFrameView = mf;
initComponents();
}
public AddMemberView(Member m) {
this.member = m;
initComponents();
}
private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {
String memberid = (this.txtMembersID.getText());
String fname= (this.txtFirstName.getText());
String mname=(this.txtMiddleName.getText());
String lname=(this.txtLastName.getText());
if(this.admin.addMember(memberid, fname,mname, lname) != null)//im having null here
{
try{
member = this.admin.searchMember(memberid);// and if i remove that 1st line of null. the next null pointer is here
String month = (String)cmbMonth.getSelectedItem();
Integer day = (Integer) cmbDay.getSelectedItem();
Integer year = (Integer)cmbYear.getSelectedItem();
String bday = month + " " + day + ", " + year;
DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.US);
Date dateBday = df.parse(bday);
String Block = this.txtBlkLotNo.getText();
String Street = (String)this.cmbStreet.getSelectedItem();
String Brgy=(String)this.cmbBarangay.getSelectedItem();
String City= (String)this.cmbCity.getSelectedItem();
String Address = Block + " " + "" + Street + " ," + Brgy + " ," + City;
String Full = fname + " " + mname + " " + lname;
int age= Integer.parseInt(this.txtAge.getText());
int contact = Integer.parseInt(this.txtContact.getText());
String region =(String) this.cmbRegion.getSelectedItem();
this.member.setFirstName(fname);// then if i remove the two my next null line is here and those who have this.**member**.setblabla.
this.member.setMiddleName(mname);
this.member.setLastName(lname);
this.member.setFullname(Full);
this.member.setLotNo(Block);
this.member.setBarangay(Brgy);
this.member.setCity(City);
this.member.setFulladdress(Address);
this.member.setBirthday(dateBday);
this.member.setAge(age);
this.member.setEmailAddress(this.txtEadd.getText());
this.member.setVotersId(this.txtVotersID.getText());
this.member.setContactNo(contact);
this.member.setRegion(region);
this.member.setMemberId(memberid);
if(this.rbtnFemale != null){
this.member.setGender(this.rbtnFemale.getLabel());
}
else{
this.member.setGender(this.rbtnFemale.getLabel());
}
}catch (ParseException ex) {
System.out.println("Exception: "+ ex.getMessage());
}
JOptionPane.showMessageDialog(this, "Info saved!");
JOptionPane.showMessageDialog(this,"Name" + this.member.getFirstName());
}
}
thanks for your help.

I think your "admin" variable is null. Do you call your constructor? If yes, are the parameters correct?
Just write "private Admin admin" dont make the admin variable an Admin Object. Try initialize it or call the constructor properly.

Related

How can I use subclass in java that I can print two different length of String?

Here is a big project, so I can just show you part of the code.
There are two different plan of membership: standard and family. When the member is standard membership, the information of that member contains(name, dob, expire date, location), but when the member's plan is family, the information of that member contains(name, dob, expire date, location, guest-pass remaining) Which means their gonna have one more element. But they have been stored in the same database. And my question is how can I print them.
The out put should be
Carl Brown, DOB: 10/7/1991, Membership expires 3/31/2023, Location: PISCATAWAY, 08854, MIDDLESEX
Jerry Brown, DOB: 6/30/1979, Membership expires 12/28/2022, Location: EDISON, 08837, MIDDLESEX, (Family) guest-pass remaining: 1
But I only get
Carl Brown, DOB: 10/7/1991, Membership expires 3/31/2023, Location: PISCATAWAY, 08854, MIDDLESEX
Jerry Brown, DOB: 6/30/1979, Membership expires 12/28/2022, Location: EDISON, 08837, MIDDLESEX
Here is my code
Member
public class Member implements Comparable<Member> {
private String fname;
private String lname;
private Date dob;
private Location location;
private Date expire = Date.getEXP();
#Override
public String toString() {
String info = String.format("%s %s, DOB: %s, Membership expires %s, Location: %s", fname, lname, dob,
expire, location);
return info;
}
public Member(String fname, String lname, Date dob, Location location) {
this.fname = fname;
this.lname = lname;
this.dob = dob;
this.location = location;
}
public String getFname() {
return fname;
}
public String getLname() {
return lname;
}
public Date getDOB() {
return dob;
}
public Date getEXP() {
return expire;
}
public Location getLocation() {
return location;
}
}
And it asked me to use subclass to get a Family plan,so I write this
Family
public class Family extends Member{
private int gpRemaining;
public Family(String fname, String lname, Date dob, Location location, int gpRemaining) {
super(fname, lname, dob, location);
this.gpRemaining = gpRemaining;
}
#Override
public String toString() {
String info = String.format("%s %s, DOB: %s, Membership expires %s, Location: %s, (Family) " +
"guest-pass remaining:" + " %d", this.getFname(), this.getLname(), this.getDOB(),
this.getEXP(), this.getLocation(), gpRemaining);
return info;
}
public int getGpRemaining() {
return gpRemaining;
}
}
And here is the MemberDatabase print method:
public class MemberDatabase {
private Member[] mlist;
private int size = 0;
private int capacity = 4;
public MemberDatabase() {
mlist = new Member[capacity];
}
public int getSize() {
return size;
}
private int find(Member member) {
for (int indexOfMember = 0; indexOfMember < size; indexOfMember++) {
if(mlist[indexOfMember].equals(member)) {
return indexOfMember;
}
}
return -1;
}
private void grow() {
capacity += 4;
mlist = Arrays.copyOf(mlist, capacity);
}
public boolean add(Member member) {
if (find(member) != -1) {
return false;
} else {
if (size >= capacity) {
return false;
}
if (size != 0 && (find(member) != -1)) {
return false;
}
mlist[size++] = member;
if (size >= capacity) {
grow();
}
return true;
}
}
public boolean remove(Member member) {
if (member == null) {
return false;
}
int indexOfMember = find(member);
if (indexOfMember != -1) {
mlist[indexOfMember] = mlist[--size];
mlist[size] = null;
return true;
}
return false;
}
/**
* Print the original membership database
*/
public void print() {
if (size == 0) {
System.out.println("Member database is empty!");
return;
}
System.out.println("\n-list of members-");
for (int i = 0; i < size; i++) {
System.out.println(mlist[i]);
}
System.out.println("-end of list-\n");
}
Here is the addmethod which Add the members:
The input is like
A Carl Brown, 10/7/1991, Piscataway
AF Jerry Brown 6/30/1979 Edison
case A means this member has standard membership which means the
output should be
> Carl Brown, DOB: 10/7/1991, Membership expires 3/31/2023, Location: PISCATAWAY, 08854, MIDDLESEX
public void run() {
System.out.println("Gym Manager running...");
String input;
String[] inputs;
creatClass();
while (scan.hasNext()) {
input = scan.nextLine();
inputs = input.split("\\s");
if (input.length() == 0) {
System.out.println();
continue;
}
switch (inputs[0]) {
case "A" -> A(inputs);
case "AF" -> AF(inputs);
private void A(String[] input) {
String[] dobDate = input[3].split("/");
Date dob = new Date(Integer.parseInt(dobDate[0]), Integer.parseInt(dobDate[1]), Integer.parseInt(dobDate[2]));
if (isValidLocation(input[4])) {
if (isValidDOB(dob)) {
Member member = new Member(input[1], input[2], dob, Location.valueOf(input[4].toUpperCase()));
if (member !=null) {
if (!database.add(member)) {
System.out.println(input[1] + " " + input[2] + " is already in the database.");
} else System.out.println(input[1] + " " + input[2] + " added.");
}
}
}
}
/**
Case AP means that the member has family membership and the output should be
Jerry Brown, DOB: 6/30/1979, Membership expires 12/28/2022, Location: EDISON, 08837, MIDDLESEX, (Family) guest-pass remaining: 1
*/
private void AP (String[] input) {
String[] dobDate = input[3].split("/");
Date dob = new Date(Integer.parseInt(dobDate[0]), Integer.parseInt(dobDate[1]), Integer.parseInt(dobDate[2]));
if (isValidLocation(input[4])) {
if (isValidDOB(dob)) {
Family member = new Family(input[1], input[2], dob, Location.valueOf(input[4].toUpperCase()), 1);
if (member !=null) {
if (!database.add(member)) {
System.out.println(input[1] + " " + input[2] + " is already in the database.");
} else System.out.println(input[1] + " " + input[2] + " added.");
}
}
}
}
Please help!!

Pass a created object from one class to another and add to ArrayList?

I´ve created a function where you add a result for a participant in a event.
Now I want to pass the created object to an addResult-method in my participant class and thereafter add it to an ArrayList in the same class, but I can´t really figure out how to do this. I´ve been stuck on this for a while, and could need some help how to approach this further.
This is what I´ve coded so far for this:
public Participant getParticipant() {
int startNumber = readInt();
boolean participantFound = false;
for (int i = 0; i < allParticipants.size(); i++) {
if (allParticipants.get(i).getStartNumber() == (startNumber)) {
participantFound = true;
return allParticipants.get(i);
}
}
if (!participantFound) {
System.out.println("No participant with number " + startNumber + " exists. " + "\n");
runCommandLoop();
}
return null;
}
public Event getEvent() {
String eventName = norm();
boolean eventFound = false;
for (int a = 0; a < allEvents.size(); a++) {
if (allEvents.get(a).getEventName().equalsIgnoreCase(eventName)) {
eventFound = true;
return allEvents.get(a);
}
}
if (!eventFound) {
System.out.println("No event called " + eventName + " found! ");
runCommandLoop();
}
else {
System.out.println("To many attempts! ");
runCommandLoop();
}
return null;
}
public void addResult() {
System.out.println("Number: ");
Participant p = getParticipant();
if (p == null) {
}
System.out.println("Event: ");
Event e = getEvent();
if (e == null) {
}
System.out.println("Type in the result for " + p.getFirstName() + " " + p.getLastName() + " in "
+ e.getEventName() + ": ");
double result = readDouble();
while (result < 0) {
System.out.println("Must be greater than or equal to zero! Try again: ");
result = readDouble();
}
Result r = new Result();
**// THIS IS WHERE I´M STUCK RIGHT NOW**
r.addResult();
System.out.println("The result " + result + " is now registred");
}
And this is my Participant class:
import java.util.ArrayList;
public class Participant {
public ArrayList<Result> allResults = new ArrayList<>();
private String firstName;
private String lastName;
private String team;
private int startNumber;
public Participant(String firstName, String lastName, String team, int startNumber) {
this.firstName = firstName;
this.lastName = lastName;
this.team = team;
this.startNumber = startNumber;
}
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 getTeam() {
return team;
}
public void setTeam(String team) {
this.team = team;
}
public int getStartNumber() {
return startNumber;
}
public void setStartNumber(int startNumber) {
this.startNumber = startNumber;
}
public void addResult(Result r) {
allResults.add(r);
}
public String toString() {
return "\n" + "Name: " + firstName + "\n" + "Last name: " + lastName + "\n" + "Team: " + team + "\n"
+ "Start number: " + startNumber;
}
}
And my Result class:
public class Result {
private double result;
public Result(double result) {
this.result = result;
}
public double getResult() {
return result;
}
public void setResult(double result) {
this.result = result;
}
public void printResult() {
System.out.println(result);
}
}
What you are doing is
Result r = new Result();
**// THIS IS WHERE I´M STUCK RIGHT NOW**
r.addResult();
but I do not see addResult() Method in Result Class. What you need to do is
p.addResult(r); // p is your Participant
hope this helps

DAO "IF" error when adding a company to contact

I'm creating a restaurant booking system and I have created the customer class but as part of the class you have be able to extend it so a company can add a contact.
I have a customer class, a company class and a TextCustomerDAO. inside the DAO is where i'm getting the error. When I try to say "If 'Y" then add a company contact" if no then just add customer. I can just add customer but when I try to add in the company contact i get an error
TextCustomerDAO: error just after the if statement where it says
contact = companyContact.getContact();
package projects.dao.textdao;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Path;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import projects.Customer;
import restaurant.dao.CustomerDAO;
import projects.Company;
public class TextCustomerDAO extends CustomerDAO {
static final char DELIMITER=':';
#Override
public List<Customer> loadCustomers(Path path) {
List<Customer> customers = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(path.toString()))) {
Customer c = null;
Company co = null;
int customerId;
String customerName, customerPhone, customerAddress, customerEmail, contact;
String[] temp;
String line = br.readLine();
while(line!=null){
temp=line.split(Character.toString(DELIMITER));
customerId = Integer.parseInt(temp[0]);
customerName = temp[1];
customerPhone = temp[2];
customerAddress = temp[3];
customerEmail = temp[4];
if (temp.length==6){
String companyContact = temp[5];
contact = companyContact.getContact();
co = new Company(customerId, customerName, customerPhone, customerAddress, customerEmail, contact);
customers.add(co);
}
else {
c = new Customer(customerId,customerName, customerPhone, customerAddress, customerEmail);
customers.add(c);
}
line = br.readLine();
}
br.close();
} catch (IOException ex) {
Logger.getLogger(TextCustomerDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return customers;
}
#Override
public void storeCustomers(Path path, List<Customer> customers) {
try (PrintWriter output = new PrintWriter(path.toFile())) {
for (Customer c:customers) {
output.println(toFileString(c));
}
output.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(TextCustomerDAO.class.getName()).log(Level.SEVERE, null, ex);
}
}
public String toFileString(Customer c) {
return Integer.toString(c.getCustomerId()) + DELIMITER +
c.getCustomerName() + DELIMITER +
c.getCustomerPhone() + DELIMITER +
c.getCustomerAddress() + DELIMITER +
c.getCustomerEmail() + DELIMITER;
}
public String toFileString(Company co) {
return Integer.toString(co.getCustomerId()) + DELIMITER +
co.getCustomerName() + DELIMITER +
co.getCustomerPhone() + DELIMITER +
co.getCustomerAddress() + DELIMITER +
co.getCustomerEmail() + DELIMITER +
co.getContact() + DELIMITER;
}
}
Customer Class:
public class Customer{
private int customerId;
private String customerName;
private String customerPhone;
private String customerAddress;
private String customerEmail;
private static int numberOfCustomers=0;
public Customer()
{
this.customerId = 0;
this.customerName = null;
this.customerPhone = null;
this.customerAddress = null;
this.customerEmail = null;
numberOfCustomers++;
}
public Customer(int customerId, String customerName, String customerPhone,
String customerAddress, String customerEmail)
{
this.customerId = customerId;
this.customerName = customerName;
this.customerPhone = customerPhone;
this.customerAddress = customerAddress;
this.customerEmail = customerEmail;
numberOfCustomers++;
}
public static int getNumberOfCustomers() {
return numberOfCustomers;
}
public int getCustomerId()
{
return customerId;
}
public void setCustomerId(int customerId)
{
this.customerId = customerId;
}
public String getCustomerName()
{
return customerName;
}
public void setCustomerName(String customerName)
{
this.customerName = customerName;
}
public String getCustomerPhone()
{
return customerPhone;
}
public void setCustomerPhone(String customerPhone)
{
this.customerPhone = customerPhone;
}
public String getCustomerAddress()
{
return customerAddress;
}
public void setCustomerAddress(String customerAddress)
{
this.customerAddress = customerAddress;
}
public String getCustomerEmail()
{
return customerEmail;
}
public void setCustomerEmail(String customerEmail)
{
this.customerEmail = customerEmail;
}
#Override
public String toString() {
return "customer id: " + getCustomerId() + ", " +
"customer name: " + getCustomerName() + ", " +
"customer phone: " + getCustomerPhone() + ", " +
"customer address: " + getCustomerAddress() + ", " +
"customer email: " + getCustomerEmail();
}
}
Company Class:
package projects;
public class Company extends Customer {
private String contact;
public Company() {
super();
this.contact = null;
}
public Company(int customerId, String customerName, String customerPhone, String customerAddress, String customerEmail, String contact) {
super(customerId, customerName, customerPhone, customerAddress, customerEmail);
this.contact = contact;
}
public String getContact() {
return this.contact;
}
public void setContact(String contact) {
this.contact = contact;
}
#Override
public String toString() {
return super.toString() + "Company Contact" + getContact();
}
}
Sorry if this is an obvious error but i have been trying for some time to fix the problem. If someone could assist or point me in the right direction it would be greatly appreciated.
Thanks

NullPointerException when Initializing new object

I have a class called CustomerRecord, that another Class, CustomerList contains. When Customer List initializes, everything is fine, but when the first instance of Customer record initializes I get a Null Pointer Exception. Im not sure why this keeps happening but I would much appreciate some help on what is wrong and how to fix it.
Exception in thread "main" java.lang.NullPointerException
at CustomerList.getCustomerList(CustomerList.java:31)
at Assignment3.main(Assignment3.java:16)
Here is my code
public class CustomerRecord {
private int customerNumber;
private String firstName;
private String lastName;
private double balance;
public CustomerRecord() {
super();
}
public int getCustomerNumber() {
return customerNumber;
}
public void setCustomerNumber(int customerNumber) {
this.customerNumber = customerNumber;
}
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 double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public String toString(){
return this.customerNumber + " " + this.firstName + " " + this.lastName + " " + this.balance;
}
}
Here is my CustomerList Code
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class CustomerList {
private int count;
private CustomerRecord[] data;
public CustomerList(){
count = 0;
CustomerRecord[] data = new CustomerRecord[100];
}
public void getCustomerList (String fileName){
Scanner fileScan;
try {
fileScan = new Scanner(new File(fileName));
while (fileScan.hasNext()){
if (fileScan.hasNextInt()){
int customerNumber = fileScan.nextInt();
String firstName = fileScan.next();
String lastName = fileScan.next();
double TransactionAmount = fileScan.nextDouble();
data[customerNumber].setBalance(data[customerNumber].getBalance() + TransactionAmount);
}
else{
data[count] = new CustomerRecord();
data[count].setCustomerNumber(count);
data[count].setFirstName(fileScan.next());
data[count].setLastName(fileScan.next());
data[count].setBalance(fileScan.nextDouble());
count++;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public CustomerRecord getCustomer (int customerNumber){
if (data[customerNumber] != null){
return data[customerNumber];
}
else
return null;
}
}
When you initialized data in the constructor you weren't actually referring to the same 'data' you had defined. You created a new data and set it to have 100 positions. But you defined it inside the constructor, so it didn't affect your global variable. What you need to do is replace CustomerRecord[] data = new CustomerRecord[100]; for data = new CustomerRecord[100];

adding objects to an ArrayList using an abstract class

I'm trying to add animal objects to a pet ArrayList using an accept method but I am getting an error saying cannot find symbol. I've been over it a bunch of times and am just not seeing it.
Thanks for your help.
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Scanner;
public class Shelter2 implements AnimalShelter {
private ArrayList<Animal2> pet;
private int Id;
Scanner in = new Scanner(System.in);
public Shelter2() {
pet = new ArrayList<Animal2>();
SimpleDateFormat DateFormat = new SimpleDateFormat("MM-dd-yyyy");
Date now = new Date();
String today = DateFormat.format(now).toString();
// pet.add(new Cat("Snow White", "Domestic Short Hair", "White", "F",
// "01-01-2012", null));
// pet.add(new Dog("Buster", "Beagle", "Brown/White/Black", "male",
// "12-25-2011", null));
// pet.add(new Reptile("Jack", "Lizard", "01-31-2012", null));
}
public String allAnimals() {
String str = "";
for (Animal2 p : pet) {
str = str + p + "\n\n";
}
return str;
}
public String available() {
String str = "";
for (int i = 0; i < pet.size(); i++) {
Animal2 p = pet.get(i);
if (p.getAdoptedDate() == null) {
str = str + p + "\n\n";
}
}
return str;
}
public String adopted() {
String str = "";
for (int i = 0; i < pet.size(); i++) {
Animal2 p = pet.get(i);
if (p.getAdoptedDate() != null) {
str = str + p + "\n\n";
}
}
return str;
}
public boolean adopt(int id) {
return true;
}
public boolean accept(Animal2 pet) {
String type = null;
System.out.println("What type of animal? (Cat, Dog, Reptile)");
type = in.next();
if (type == "Cat") {
System.out.println("Enter name: ");
String name = in.next();
System.out.println("Enter description: ");
String desc = in.next();
System.out.println("Enter color: ");
String color = in.next();
System.out.println("Enter sex: ");
String sex = in.next();
pet.add(new Cat(name, desc, color, sex, null, null));
}
return true;
}
}
public abstract class Animal2 {
public String name;
public String arrivalDate;
public String adoptedDate;
public String getName() {
return new String(name);
}
public void setName(String name) {
this.name = name;
}
public String getArrivalDate() {
return new String(arrivalDate);
}
public void setArrivalDate(String arrivalDate) {
this.arrivalDate = arrivalDate;
}
public String getAdoptedDate() {
return adoptedDate;
}
public void setAdoptedDate(String adoptedDate) {
this.adoptedDate = adoptedDate;
}
#Override
public String toString() {
return "\nName: " + name + "\nArrival Date: " + arrivalDate
+ "\nAdopted Date: " + adoptedDate;
}
}
class Cat extends Animal2 {
String desc;
String color;
String sex;
char s;
Cat(String name, String desc, String color, String sex, String arrivalDate,
String adoptedDate) {
super.setName(name);
super.setArrivalDate(arrivalDate);
super.setAdoptedDate(adoptedDate);
setDesc(desc);
setColor(color);
setSex(sex);
char s = ' ';
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
s = sex.toLowerCase().charAt(0);
if ((s == 'f') || (s == 'm')) {
this.sex = sex;
} else {
System.err.println("Illegal value for Cat sex field - " + sex);
}
}
#Override
public String toString() {
if (s == 'f') {
sex = "Female";
} else if (s == 'm') {
sex = "Male";
} else {
sex = null;
}
return "\nCat: " + super.toString() + "\nDescription: " + desc
+ "\nColor: " + color + "\nSex: " + sex;
}
}
class Dog extends Animal2 {
String bred;
String color;
String sex;
char s;
Dog(String name, String bred, String color, String sex, String arrivalDate,
String adoptedDate) {
super.setName(name);
super.setArrivalDate(arrivalDate);
super.setAdoptedDate(adoptedDate);
setBred(bred);
setColor(color);
setSex(sex);
char s = ' ';
}
public String getBred() {
return bred;
}
public void setBred(String bred) {
this.bred = bred;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
s = sex.toLowerCase().charAt(0);
if ((s == 'f') || (s == 'm')) {
this.sex = sex;
} else {
System.err.println("Illegal value for Dog sex field - " + sex);
}
}
#Override
public String toString() {
if (s == 'f') {
sex = "Female";
} else if (s == 'm') {
sex = "Male";
} else {
sex = null;
}
return "Dog: " + super.toString() + "\nBred: " + bred + "\nColor: "
+ color + "\nSex: " + sex;
}
}
class Reptile extends Animal2 {
String type;
Reptile(String name, String type, String arrivalDate, String adoptedDate) {
super.setName(name);
super.setArrivalDate(arrivalDate);
super.setAdoptedDate(adoptedDate);
setType(type);
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
#Override
public String toString() {
return "Reptile: " + super.toString() + "\nType: " + type;
}
}
I'm going to go out on a limb here and say that this line is giving you the error:
pet.add(new Cat(name, desc, color, sex, null, null));
You're getting this error because pet, within the scope of your accept method, is an Animal2. If you want to reference the field named pet, try:
this.pet.add(new Cat(name, desc, color, sex, null, null));
Also, in your Dog and Cat classes, you are not setting s. You are creating a new variable s and setting it to ' ' (char s = ' ';). I'm not sure how that will affect your project, but you probably aren't intending to do it.

Categories

Resources