I am trying to figure out Inheritance and Arrays in Java and I am trying to get these classes to work together. I believe I have the Inheritance down, but I am still struggling with the array part.
There are three files: 1. Person.java -base class 2. Student.java -a derived class of Person.java 3. Family.java -not quite sure, I think it's its own base class
Person.java has two instance variables, String name and int age, and an assortment of constructors, toString, equals, and set/get methods
Student.java, again, a derived class of Person, by definition will have all the stuff contained within Person, as well as two more instance vars, String major, and double gpa. This class also have get/set methods for major and gpa, an equals method that compares one class student with another class student, and I believe it's called an overidden method of toString that returns name, age, major, and gpa all in one string.
Lastly, Family.java is where the main method resides. It creates an array of type Person, adds "Persons" to this array, then outputs them.
I am getting an error that says: "main" java.lang.ArrayIndexOutOfBoundsException: 8
I can not figure out why this program is not working properly and would appreciate any help to figure this out. Thank you.
Person.java Class
public class Person
{
private String name;
private int age;
public Person()
{
name = "John Smith";
age = 1;
}
public Person(String n, int a)
{
name = n;
age = a;
}
public String toString()
{
return ("Name: " + getName() + ", Age: " + age + " ");
}
public boolean equals(Person otherPerson)
{
return (getName().equals(otherPerson.getName()) && (age == otherPerson.age));
}
public String getName()
{
return name;
}
public void setName(String newName)
{
name = newName;
}
public int getAge()
{
return age;
}
public void setAge(int newAge)
{
age = newAge;
}
}
Student.java Class
public class Student extends Person
{
private String major;
private double gpa;
public Student()
{
super();
major = "Undecided";
gpa = 0.0;
}
public Student(String theName, int theAge, String theMajor, double theGpa)
{
super(theName, theAge);
setMajor(theMajor);
setGpa(theGpa);
}
public String toString()
{
return ("Name: " + getName() + ", Age: " + getAge() + ", Major: " + major + ", GPA: " + gpa);
}
public boolean equals(Student otherStudent)
{
return (major.equals(otherStudent.major) && (gpa == otherStudent.gpa));
}
public String getMajor()
{
return major;
}
public void setMajor(String newMajor)
{
major = newMajor;
}
public double getGpa()
{
return gpa;
}
public void setGpa(double newGpa)
{
gpa = newGpa;
}
}
Family.java Class
public class Family
{
private int famArray = 0;
private Person[] family;
public Family(int size_of_family)
{
famArray = size_of_family;
family = new Person[famArray];
}
public void addPerson(Person p)
{
boolean isPresent = false;
int i;
for(i = 0; i < family.length; i++)
{
if(family[i] != null && family[i].equals(p))
{
isPresent = true;
System.out.println(p.getName() +
" is already present in the family");
}
}
if(isPresent == false)
family[i] = p;
}
public void printOutFamily()
{
for(int i = 0; i < family.length; i++)
{
System.out.println(family[i].toString());
}
}
public static void main(String[] args)
{
Family f = new Family(8);
Person fred= new Person("Fred Flintstone", 50);
System.out.println("created " + fred);
f.addPerson(fred);
f.addPerson(fred);
Student fredStudent = new Student("Fred Flintstone", 50, "Math", 3.1);
System.out.println("created "+ fredStudent);
f.addPerson(fredStudent);
Person wilma = new Person("Wilma Flintstone", 48);
f.addPerson(wilma);
Student george= new Student("George", 21, "Politics", 3.1);
System.out.println("created " + george);
f.addPerson(george);
george.setName("Georgie");
f.addPerson(new Student("George", 21, "Politics", 3.1));
f.addPerson(new Student("John", 18, "Geology", 2.9));
f.addPerson(new Student("Jane", 21, "Music", 3.2));
f.addPerson(new Student("Tarzan", 22, "Gymnastics", 4.0));
f.addPerson(new Student("Jim", 21, "Physics", 2.5));
System.out.println("****** family listing: ");
f.printOutFamily();
}
}
Here's the problem, in Family#addPerson method:
if(isPresent == false)
family[i] = p;
You're adding the element in position i. If the element is not found, then i value will be family.length, thus giving you the exception.
Use int famArray field instead:
if(isPresent == false) {
family[famArray++] = p;
}
Or in an easier way for starters:
if(isPresent == false) {
family[famArray] = p;
famArray = famArray + 1;
}
As an addition to your current problem, you should first check if the famArray element is equals to family.length. If they're the same, then increase the array or do not allow more elements.
You state you have the same problem. This is because you're initializing famArray with the length of the array, noted in Family class constructor:
public Family(int size_of_family) {
famArray = size_of_family; //here
family = new Person[famArray];
}
Change the code to:
public Family(int size_of_family) {
famArray = 0;
family = new Person[size_of_family];
}
And you're done.
The problem is the line
family[i] = p;
This occurs after a for loop which increments i to be equal to the length of the array. I don't have any suggestions to fix it because I'm not sure what you are trying to do here.
Related
Getting stuck with my Travail System Project, Confusing a little bit about understanding that if there Classes called Bookable, Hotel and BookingSystem.
Hotel class is implements Bookable. Furthermore, BookingSystem Class is composition from Bookable, So, I need to create method at BookingSystem class which called addHotel.
what I must do about it to make a relationship between Hotel Class and BookingSystem Class.
Thanks In Advance.
Israa
Hotal Class:
public class Hotel implements Bookable {
private String name, location;
private int noOfRooms;
private double roomPrice;
private Date bookingDate;
private ArrayList<Integer> bookedRooms = new ArrayList<Integer>();
private ArrayList<Integer> numberOfrooms = new ArrayList<Integer>();
public Hotel() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public int getNoOfRooms() {
return noOfRooms;
}
public void setNoOfRooms(int noOfRooms) {
this.noOfRooms = noOfRooms;
}
public double getRoomPrice() {
return roomPrice;
}
public void setRoomPrice(double roomPrice) {
this.roomPrice = roomPrice;
}
public Date getBookingDate() {
return bookingDate;
}
public void setBookingDate(Date bookingDate) {
this.bookingDate = bookingDate;
}
public ArrayList<Integer> getBookedRooms() {
return bookedRooms;
}
public void setBookedRooms(ArrayList<Integer> bookedRooms) {
this.bookedRooms = bookedRooms;
}
public String Book() {
if ( numberOfrooms.size() != (bookedRooms.size())) {
for (int i = 0; i < bookedRooms.size(); i++) {
int oldVal = bookedRooms.get(i);
int newVal = oldVal + 1;
bookedRooms.add(bookedRooms.set(i, newVal));
}
}
return null;
}
}
Bookable class:
public interface Bookable {
public String Book();
}
BookingSytsem Class:
public class BookingSystem {
private ArrayList<Customer> customer = new ArrayList<Customer>();
private ArrayList<Bookable> bookable = new ArrayList<Bookable>();
private ArrayList<Operation> operation = new ArrayList<Operation>();
public BookingSystem() {
}
// **
public void addCustomer(String name, int id) {
Customer customers = new Customer(id, name);
customer.add(customers);
System.out.println("new customer " + customers.getName() + " added");
}
// **
public void deleteCustomer(String name, int id) {
Customer customers = new Customer(id, name);
if (customer.contains(name)) {
customer.remove(name);
}
System.out.println("Customer " + customers.getName() + " deleted");
}
public Customer findCustomer(int id) {
for (Customer c : customer) {
if (c.getId() == id) {
return c;
}
}
return null;
}
public void addHotel() {
Hotel H1 = new Hotel();
Scanner name = new Scanner(System.in);
System.out.println("Please Enter the name of Hotel: ");
String n1 = name.nextLine();
bookable.add(H1);
System.out.println("The Hotel " + name + "added");
}
public void makeABooking(Customer c, Bookable b) {
Scanner input =new Scanner(System.in);
System.out.println("Please Enter your name: ");
String name = input.nextLine();
System.out.println("Please Enter your ID: ");
int ID = input.nextInt();
while(true) {
if(ID == -1 && ID == 0) {
System.out.println("Invalid ID. Enter again: ");
name = input.nextLine();
System.out.println("Please Enter your ID: ");
ID = input.nextInt();
}
}
}
}
(Your question is more suitable to https://softwareengineering.stackexchange.com/ - recommend asking it there...)
General speaking it wouldn't make sense to have a Hotel without a name, location or number of rooms so I'd recommend adding a constructor with minimal required information:
public Hotel (String name, String location, int rooms) {
this.name = name;
this.location = location;
this.noOfRooms = rooms;
}
bookingDate makes no sense as a single property of a hotel but rather a property of each booked room so you have a design issue - this is not addressed here.
Again, roomPrice usually varies by room so in a robust solution this would be a property of a room not a hotel - not addressed here.
Why is there a noOfRooms and a numberOfRooms list. In fact, the numberOfRooms list doesn't make sense as a list. I'd just keep the noOfRooms and get rid of numberOfRooms.
An implied property, nbrOfAvailableRooms can be derived from noOfRooms - bookedRooms.size();
I would assume your bookedRooms is a list of room numbers which are booked but that's not possible to tell from your implementation. You should focus on what you want Book to do.
The Book interface method is not documented but it looks like it should simply take an available asset (room) and consider it booked. It should return a boolean success not a String - especially not null.
I recommend writing (in pseudo code) what you want a Book implementation to do - include that in question. That is the core issue you are having.
Here, I have a superclass called 'Staff'. My main method is in a separate class called 'Program_2A'. The filename given is Program_2A.java. Eclipse is showing an error in the second line of the program saying
Link all references for a local rename (does not change references in other files)
I don't understand what's wrong by having the main class, not as a superclass.
Here is the code:
import java.util.*;
public class Staff {
private int Staff_ID;
private String Name;
private int Phone;
private int Salary;
public Staff(int staff_id, String name, int phone, int salary)
{
Staff_ID = staff_id;
Name = name;
Phone = phone;
Salary = salary;
}
public void display()
{
System.out.println("\t" + Staff_ID + "\t" + Name + "\t" + Phone + "\t" + Salary);
}
}
class Teaching extends Staff
{
private String Domain;
private int Publication;
public Teaching(int staff_id, String name, int phone, int salary, String domain, int publication) {
super(staff_id,name,phone,salary);
Domain = domain;
Publication = publication;
}
public void display() {
super.display();
System.out.println("\t" + Domain + "\t" + Publication);
}
}
class Technical extends Staff
{
private String Skills;
public Technical(int staff_id, String name, int phone, int salary, String skills) {
super(staff_id,name,phone,salary);
Skills = skills;
}
public void display() {
super.display();
System.out.println("\t" + Skills);
}
}
class Contract extends Staff
{
private int Contract;
public Contract(int staff_id, String name, int phone, int salary, int contract) {
super(staff_id,name,phone,salary);
Contract = contract;
}
public void display() {
super.display();
System.out.println("\t" + Contract);
}
}
class Program_2A {
public static void main(String[] args) {
Staff St[] = new Staff[3];
St[0] = new Teaching(1, "ABC", 1234, 10000, "CSE", 3);
St[1] = new Technical(2, "DEF", 5678, 200000, "C++");
St[2] = new Contract(3, "GHI", 9012, 50000, 3);
System.out.println("STAFF ID \t NAME \t PHONE \t SALARY \t DOMAIN \t PUBLICATIONS \t SKILLS \t PERIOD");
for(int i=0;i<3;i++) {
St[i].display();
System.out.println();
}
}
}
In Java, one file can only contain one public class.
So please change class Program_2A to public class Program_2A and remove public keyword before Staff class.
I am trying to call on a variable numFriends I created in another class but when I try to do so, it says "numFriends cannot be resolved to a variable". The variable is incremented each time a new friend is added and I want to display that in my Test class. Here's my code:
CLASS ONE
public class Person {
private String fullName;
private char gender;
private int age;
public static int numFriends = 0;
public Person(String nm, char gen, int a) {
fullName = nm;
gender = gen;
age = a;
numFriends++;
}
public void setName(String nm) {
fullName = nm;
}
public void setAge(int a) {
age = a;
}
public int getAge() {
return age;
}
public void setGender(char g) {
gender = g;
}
public String toString() {
return (fullName + ", gender = " + gender + ", age = " + age );
}
}
CLASS TWO (executable)
public class TestPerson {
public static void main(String[] args) {
System.out.println(numFriends + " people at first");
Person p1 = new Person("Otto Mattik", 'M', 22);
p1.setName("Otto Mattik");
p1.setGender('M');
p1.setAge(22);
System.out.println("Person Full Name = " + p1);
Person p2 = new Person("Anna Bollick", 'F', 19);
p2.setName("Anna Bollick");
p2.setGender('F');
p2.setAge(19);
System.out.println("Person Full Name = " + p2);
Person p3 = new Person("Dick Tator", 'M', 33);
p3.setName("Dick Tator");
p3.setGender('M');
p3.setAge(33);
System.out.println("Person Full Name = " + p3);
changeName(p2, "Anna Bollik-Mattik");
Person[] people = {
p1, p2, p3
};
agePersons(people, 5);
System.out.println("\n" + numFriends + " people after 5 years");
for (Person person : people)
System.out.println("Person fullName: " + person);
}
public static void changeName(Person p, String name) {
p.setName(name);
}
public static void agePersons(Person[] people, int years) {
for (Person person : people)
person.setAge(person.getAge() + years);
}
}
You need to say Person.numFriends. This is because numFriends is a static member of the Person class, so you need to use the Person class to reference numFriends.
I have class Employe that has variables like id , name ... and 2 other classes that inherit from Employe : Seller and Cashier.
To calculate their salaries, I created a method in each one of Seller and Cashier but I need to access the name via the name getter method in Employe so I'd have :
System.out.println("The salary is "+Seller.getName() +" is : " +salary);
Once I type that, I get an error sayingI need to make the name variable to static, but I need it as non static since I'm creating multiple objects using the name variable.
Any solution to this problem?
EDIT :
This is the Employe class :
public class Employe {
protected int id;
protected String name;
protected String adresse;
protected int nbrHours;
public Employe () {
}
public Employe (int id, String name, String adresse, int nbHours)
{
this.id=id;
this.name=name;
this.adresse=adresse;
this.nbrHours=nbHours;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setNom(String name) {
this.name = name;
}
public String getAdresse() {
return adresse;
}
public void setAdresse(String adresse) {
this.adresse = adresse;
}
}
This is the Seller class :
public class Seller extends Employe {
private int prime;
public Seller (int id, String name, String adresse, int nbHours,int prime)
{
super(id,name,adresse,nbHours);
this.prime=prime;
}
public int getPrime() {
return prime;
}
public void setPrime(int prime) {
this.prime = prime;
}
#Override
public String toString() {
return super.toString() +" [prime=" + prime + "]";
}
public void salaireSeller ()
{
int salaire = 0;
if(nbrHours<160)
{
salaire = nbrHours * 10 + prime;
System.out.println("La salaire de "+Responsable.getName() +" est : " +salaire);
}
else if(nbrHours >160)
{
int Extra= (160 - nbrHours) * 12;
int salaire1 = 160 * 10000 + prime;
salaire= Extra + salaire1;
System.out.println("La salaire de "+Seller.getName() +" est : " +salaire);
}
}
In the Main class I created a Seller object :
Seller Sel1 = new Seller(2, "Alex", "Miami", 18, 200);
now I want to calculat its salary using the SalaireSeller() method in the Main class of course :
Sel1.salaireSeller();
but in the Seller class :
System.out.println("La salaire de "+Responsable.getName() +" est : " +salaire);
it says I need to set Name to static, this will give every object the same name
You need a Seller instance, to call getName() and getSalary() on.
Seller s = new Seller();
// ...
System.out.println("The salary is " + s.getName() +
" is : " + s.getSalary());
You're certainly trying to access an instance variable from a static method.
What you want to do here is to create an instance of your class, then call the getName() method on the object created.
Seller sell = new Seller();
sell.setName("Jean-Paul"); // This is just an example
System.out.println("His name is " + sell.getName()); // Prints : His name is Jean-Paul
I figuered out a solution, I just need to add the name to the toString() method in class Employee, then add the salary variable to the toString() method in Seller class, without System.out.println(..) in SalaireSeller().
or instead of Seller.getName(), I use this.getName() and it works.
I have a Query I have developed a pojo ..
public class Customer {
int Age;
public Customer(int age, String surname, String forename) {
super();
Age = age;
Surname = surname;
Forename = forename;
}
String Surname,Forename;
public int getAge() {
// TODO Auto-generated method stub
return Age;
}
public String getSurname() {
// TODO Auto-generated method stub
return Surname;
}
public String getForename() {
// TODO Auto-generated method stub
return Surname;
}
public void display()
{
// System.out.println(Forename+"\t"+Surname+"\t"+Age);
System.out.println(Age+"\t"+Forename+"\t"+Surname);
}
}
and here is my collection class ..
class testCustomerComparator
{
public static void main(String... a)
{
Customer customerFirst = new Customer(46,"Alabama", "Christonson");
Customer customerSecond = new Customer(21, "Anna", "Sobek");
Customer customerThird = new Customer(27, "Rafael", "Sobek");
List<Customer> list = new ArrayList<Customer>();
list.add(customerThird);
list.add(customerSecond);
list.add(customerFirst);
}
}
please advise me How to make comprator for this class , I want to make comparator so that a list of customers get sorted by age and second by surname. After that you want to sort by forename. please advise I have nesting condition inside comparator
lOGIC MUST BE SOMETHING LIKE...
public class CustomerComparator implements Comparator<Customer> {
#Override
public int compare(Customer c1, Customer c2) {
if (c1.getAge() == c2.getAge()) {
if (c1.getSurname().compareTo(c2.getSurname()) == 0) {
return c1.getForename().compareTo(c2.getForename()) {
} else {
return c1.getSurname().compareTo(c2.getSurname());
}
} else if (c1.getAge() > b2.getAge()) {
return -1;
} else {
return 1;
}
}
but it is not working please advise
Seems much like homework. I can give you some hints in where to look at.
You have two choices:
make the POJO class extend Comparable<Customer>
define a custom external comparator as a Comparator<Customer>.
Assuming the second choice, in which you have two explicit customers, you'll have to define a method similar to this one:
#Override
public int compare(Customer c1, Customer c2)
{
// this method should return 0 if c1.equals(c2),
// should instead return 1 if c1 should come first than c2 and -1 otherwise
}
public class CustomerComparator implements Comparator<Customer> {
public int compare(Customer c1, Customer c2) {
.... here you have c1 and c2. compare returns -1 if c1 should go before c2,
0 if they are found to be equal, and 1 if c2 should go before c1.
You add the logic to compare c1 and c2 fields as you stated and return the result.
}
}
Then you use Collections.sort to sort that list using this comparator.
You can help of the below code.
import java.util.*;
class Customer {
private int age;
private String name;
private String forename;
public Customer(int age, String surname, String forename) {
super();
this.age = age;
this.name = surname;
this.forename = forename;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return this.age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setForename(String forename) {
this.forename = forename;
}
public String getForename() {
return forename;
}
}
class AgeComparator implements Comparator {
public int compare(Object emp1, Object emp2) {
int emp1Age = ((Customer) emp1).getAge();
int emp2Age = ((Customer) emp2).getAge();
if (emp1Age > emp2Age)
return 1;
else if (emp1Age < emp2Age)
return -1;
else
return 0;
}
}
/*
* The below given comparator compares employees on the basis of their name.
*/
class NameComparator implements Comparator {
public int compare(Object emp1, Object emp2) {
// parameter are of type Object, so we have to downcast it to Employee
// objects
int emp1Age = ((Customer) emp1).getAge();
int emp2Age = ((Customer) emp2).getAge();
if (emp1Age > emp2Age) {
return 1;
} else if (emp1Age < emp2Age) {
String emp1Name = ((Customer) emp1).getName();
String emp2Name = ((Customer) emp2).getName();
// uses compareTo method of String class to compare names of the
// employee
return emp1Name.compareTo(emp2Name);
} else {
return 0;
}
}
}
class CustomerComparator implements Comparator {
public int compare(Object emp1, Object emp2) {
// parameter are of type Object, so we have to downcast it to Employee
// objects
String emp1Name = ((Customer) emp1).getName();
String emp2Name = ((Customer) emp2).getName();
// uses compareTo method of String class to compare names of the
// employee
return emp1Name.compareTo(emp2Name);
}
}
public class JavaComparatorExample {
public static void main(String args[]) {
// Employee array which will hold employees
Customer employee[] = new Customer[3];
// set different attributes of the individual employee.
employee[0] = new Customer(46, "Alabama", "Christonson");
employee[1] = new Customer(21, "Anna", "Sobek");
employee[2] = new Customer(27, "Rafael", "Sobek");
System.out.println("Order of employee before sorting is");
// print array as is.
for (int i = 0; i < employee.length; i++) {
System.out.println("Employee " + (i + 1) + " name :: "
+ employee[i].getName() + ", Age :: "
+ employee[i].getAge());
}
Arrays.sort(employee, new AgeComparator());
System.out
.println("\n\nOrder of employee after sorting by employee age is");
for (int i = 0; i < employee.length; i++) {
System.out.println("Employee " + (i + 1) + " name :: "
+ employee[i].getName() + ", Age :: "
+ employee[i].getAge());
}
// Sorting array on the basis of employee Name by passing NameComparator
Arrays.sort(employee, new NameComparator());
System.out
.println("\n\nOrder of employee after sorting by employee name is");
for (int i = 0; i < employee.length; i++) {
System.out.println("Employee " + (i + 1) + " name :: "
+ employee[i].getName() + ", Age :: "
+ employee[i].getAge());
}
}
}
Hope this will help you.
EDIT
Look at the CustomerComparator class.
#Override
public int compare(Customer c1, Customer c2) {
int r = Integer.valueOf(c1.getAge()).compareTo(c2.getAge());
if (r != 0) return r;
r = c1.getSurname().compareTo(c2.getSurname());
if (r != 0) return r;
return c1.getForename().compareTo(c2.getForename());
}