I have a homework assignment problem that looks like this:
(20 pts) Create a Student class with the following:
A private String variable named “name” to store the student’s name
A private integer variable named “UFID” that contains the unique ID number for this student
A private String variable named “DOB” to store the student’s date of birth
A private integer class variable named numberOfStudents that keeps track of the number of students that have been created so far
A public constructor Student(String name, int UFID, String dob)
Several public get/set methods for all the properties
getName/setName
getUFID/setUFID
getDob/setDob
Write a test program, roster.java, that keeps a list of current enrolled students. It should have methods to be able to enroll a new
student and drop an existing student.
I'm not asking anyone to do this assignment for me, I just really need some general guidance. I think I have the Student class pretty well made, but I can't tell exactly what the addStudent() and dropStudent() methods should do - should it add an element to an array or something or just increments the number of students? The code I have so far looks like this.
public class Student {
private String name;
private int UFID;
private String DOB;
private static int numberOfStudents;
public Student(String name, int UFID, String DOB) {
this.name = name;
this.UFID = UFID;
this.DOB = DOB;
}
public String getDOB() {
return DOB;
}
public void setDOB(String dOB) {
DOB = dOB;
}
public int getUFID() {
return UFID; }
public void setUFID(int uFID) {
UFID = uFID; }
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNumberOfStudents() {
return numberOfStudents;
}
public void setNumberOfStudents(int numberOfStudents) {
Student.numberOfStudents = numberOfStudents;
}
public static void addStudent(String name, int UFID, String DOB) {
numberOfStudents++;
}
public static void dropStudent(String name) {
numberOfStudents--;
}
}
Any guidance as I finish this up would be greatly appreciated.
The assignment writes itself: you need a Roster class that owns and maintains a collection of Students:
public class Roster {
private Set<Student> roster = new HashSet<Student>();
public void addStudent(Student s) { this.roster.add(s); }
public void removeStudent(Student s) { this.roster.remove(s); }
}
Related
I have a program I am working with to help me practice my coding skills. The program has the following scenario: there is a classroom of 20 students, where the record is taken of the students' names, surnames, and age. Half of these students take part in the school's athletics. Here, record is kept of their races that they have done and the ones they've won.
In this program, I have three classes:
runStudents - class with main method
Students (String name, String surname, int age) - parental class
AthleticStudents (String name, String surname, int age, int races, int victories) - sub class
The user should be able to add another race (and win) to the object. As seen by the code provided, an Array is created to store the 20 Students objects. I have to be able to access a method to alter the object in the array, but this method is not in the parental class (the class the objects are created from.
public class Students
{
private String name;
private String surname;
private int age;
public Students()
{
}
public Students(String name, String surname, int age)
{
this.name = name;
this.surname = surname;
this.age = age;
}
public String getName()
{
return this.name;
}
public String getSurname()
{
return this.surname;
}
public double getAge()
{
return this.age;
}
public void setName(String name)
{
this.name = name;
}
public void setSurname(String surname)
{
this.surname = surname;
}
public void setAge(int age)
{
this.age = age;
}
public String toString()
{
return String.format("name\t\t: %s\nsurname\t\t: %s\nage\t\t: %s",
this.name, this.surname, this.age);
}
}
public class AthleticStudents extends Students
{
private int races;
private int victories;
public AthleticStudents()
{
}
public AthleticStudents(String name, String surname, int age, int
races, int victories)
{
super(name, surname, age);
this.races = races;
this.victories = victories;
}
public int getRaces()
{
return this.races;
}
public int getVictories()
{
return this.victories;
}
public void setRaces(int races)
{
this.races = races;
}
public void setVictories(int victories)
{
this.victories = victories;
}
public void anotherRace()
{
this.races = this.races + 1;
}
public void anotherWin()
{
this.victories = this.victories + 1;
}
public String toString()
{
return super.toString() + String.format("\nnumber of races\t:
%s\nnumber of wins\t: %s", this.races, this.victories);
}
}
public class runStudents
{
public static void main(String[]args)
{
Students[] myStudents = new Students[20];
myStudents[0] = new Students("John", "Richards", 15);
myStudents[1] = new AthleticStudents("Eva", "Grey", 14, 3, 1);
myStudents[2] = new Students("Lena", "Brie", 15);
for (int i = 0; i < 3; i++)
System.out.println(myStudents[i].toString() + "\n\n");
}
}
I want to be able to do the following:
AthleticStudents[1].anotherRace();
but cannot do so as the array object is derived from the parental class, and I declared the method in the sub class. How can I link the two?
I assume that you create an array of the parent class instances. Just cast the instance this way (you better check whether the element is the instance of a subclass):
if (AthleticStudents[1] instanceof AthleticStudents)
((AthleticStudents) AthleticStudents[1]).anotherRace();
I'm not sure if this is exactly what you're looking for but it worked well for me. Instead of trying to access AthleticStudents method anotherRace() like that, try this in your main method.
Students[] myStudents = new Students[20];
myStudents[0] = new Students("John", "Richards", 15);
myStudents[1] = new AthleticStudents("Eva", "Grey", 14, 3, 1);
myStudents[2] = new Students("Lena", "Brie", 15);
AthleticStudents addRace= (AthleticStudents)myStudents[1];
addRace.anotherRace(); //This will increment Eva's race count to 4
for (int i = 0; i < 3; i++)
System.out.println(myStudents[i].toString() + "\n\n");
All I did was cast the element into an object AthleticStudents named 'addRace'. By casting myStudents[1] to this new object you are able to access all of AthleticStudents methods.
I just saw the other answer posted which works just as well!
Hope this helps!
I’m not sure that i understand your question, because you are a bit inconsistent with your capitalization. runStudents is a class, while AthleticStudents is both a class and an array. But i’ll try.
IF i did understand your question, you have an array Student[] studentArray. Some Student objects in studentArray are AthleticStudents, others are not. You have a specific AthleticStudent eva which is in studentArray[] having let’s say index 1, and you want to add to her anotherRace(). Your call studentArray[1].anotherRace does not compile because the compiler treats that element as a Student and not as a AthleticStudent.
The trick is to cast the element to AthleticStudent. I omit the test of the element of being really an AthleticStudent; you will have to do that test in your code.
((AthleticStudent) studentArray[1]).anotherRace();
I am trying to write a program which stores information about a person in a linked list. I made a simple person class to store the name, age and addresses in the list. I would also like to store multiple addresses for EACH person, and a fact about the place in another linked list, inside the person class.
So for example, "Tara" can have a home address of "10 Central Ave" and a work address of "5 Willow street" etc. The problem is, I don't know how to have a linked list inside another.
My goal is to check whether the person's name is already on the list, and if so, add another address for them. (So that there is no repeats). I am a beginner and can really use some help.
public class Person {
private String name;
private int age;
public LinkedList <String> adresses;
public Person() {
name = "default";
age = 0;
adresses = new LinkedList<>();
}
public Person(String n, int a) {
name = n;
age = a;
}
public LinkedList<Adress> getAdresses() {
return adresses;
}
public void setAdresses(LinkedList<Adress> adresses) {
this.adresses = adresses;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString() {
return name+" "+age+" "+adresses;
}
}
public class Adress {
public String adress;
public String fact;
public Adress(String a, String f) {
adress = a;
fact = f;
}
public String getAdress() {
return adress;
}
public void setAdress(String adress) {
this.adress = adress;
}
public String getFact() {
return fact;
}
public void setFact(String fact) {
this.fact = fact;
}
}
public class Test {
public static void main(String[] args) {
Person Tara = new Person("Tara",35);
Person Judah = new Person("Judah",28);
Person Mark = new Person("Mark",45);
Person Seth = new Person("Seth",23);
LinkedList<Object> tester = new LinkedList<>();
tester.add(Tara);
tester.add(Judah);
tester.addLast(Mark);
tester.addLast(Seth);
System.out.println(tester);
}
}
How is about to use the next classic data structure for your project?
public class Person {
private String name
private int age;
public List<Address> addresses;
//...
}
I just have this basic code where I need help adding employee data to an ArrayList of another class. I am just writing this code in preparation for an assignment, so don't bash my code too much. Essentially though, i'll be needing to add elements of employees and delete them eventually. But for now, I just need help adding the elements to my other Employee class. =]
public class main {
private static Employee employee;
public static void main(String[] args) {
employee = new Employee(10,10);
System.out.println(employee.toString());
}
}
...............
import java.util.ArrayList;
public class Employee {
public int employeeNum;
public double hourRate;
ArrayList<Employee> Employee = new ArrayList<>();
public Employee(int employeeNum, double hourRate){
this.employeeNum = employeeNum;
this.hourRate = hourRate;
}
public String toString(){
return ""+employeeNum+hourRate;
}
}
Simple Example -
package com;
import java.util.ArrayList;
public class TestPage{
public static void main(String[] args){
Employee emp1, emp2;
emp1 = new Employee();
emp2 = new Employee();
emp1.setName("MAK");
emp2.setName("MICHELE");
emp1.setAddress("NY");
emp2.setAddress("WY");
//and keep putting other information like this
ArrayList<Employee> employee = new ArrayList<Employee>();
employee.add(emp1);
employee.add(emp2);
System.out.println("emp1 name is : " + employee.get(0).getName());
System.out.println("emp2 name is : " + employee.get(1).getName());
System.out.println("emp1 address is : " + employee.get(0).getAddress());
System.out.println("emp2 address is : " + employee.get(1).getAddress());
}
}
class Employee{
String name, address;
int age, salary;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
}
It seems like what you're asking is based on one employee having sub-employees and that structurally that probably represents a hierarchy (Some commenters seem to be missing that point). But that's an assumption on my part. Based on that assumption.
A little bit of feedback to start on structure of your main class:
public class main {
public static void main(String[] args) {
Employee employee = new Employee(10,10);
System.out.println(employee.toString());
}
}
It seems to me that there's no reason to have a static instance variable for that root employee instance. You should try to limit the scope of variables where possible. It seems like it could very well be in the main() method's scope.
public class Employee {
public int employeeNum;
public double hourRate;
ArrayList<Employee> employees= new ArrayList<>();
public Employee(int employeeNum, double hourRate){
this.employeeNum = employeeNum;
this.hourRate = hourRate;
}
public String toString(){
return ""+employeeNum+hourRate;
}
public ArrayList<Employee> getEmployees() {
return this.employees;
}
}
It may be better to name your arraylist employees or employeeList. I went with employees in this case because that convention is preferable.
And in relation to your question, ArrayList is pass by reference so you could just add a getter method for the sub-employee list (employees).
To add employees from your main method you could do something like
Employee rootEmployee = new Employee(5, 10.0);
rootEmployee.getEmployees().add(new Employee(6, 5.0));
Or you could add an additional method to Employee like this:
public void addEmployee(Employee e) {
employees.add(e);
}
I have a simple java program I and I cannot figure out why the setter for a class will not set the correct value.
I have a class Employee, a class Department, a class Company. Once I am able to set correct values to the fields of an Employee instance I will then store that employee in a arraylist of employees in an instance of Department(arrayList field).
The class called Employee. It has four fields, String fName, String lName, int age, String department. I am able to set fName and lName though age is always set to 0 and department is always set to null.
Here is the code for the employee class:
public class Employee {
private String fName;
private String lName;
private String department;
private int age;
//getters and setters for the private fields of the Employee class
public void setAge(int num){
num = age;
}
public int getAge(){
return age;
}
public void setDepartment(String dep){
dep = department;
}
public String getDepartment(){
return department;
}
public void setfName(String afName){
fName = afName;
}
public String getfName(){
return fName;
}
public void setlName(String alName){
lName = alName;
}
public String getlName(){
return lName;
}
}
Here is the code for a method called addEmployee:
public void AddEmployee(Department depInstance){
String firstName = JOptionPane.showInputDialog("Enter employee First name");
String lastName = JOptionPane.showInputDialog("Enter employee last name");
int empAge = Integer.parseInt(JOptionPane.showInputDialog("Enter employee age"));
String empDep = JOptionPane.showInputDialog("Enter employee department");
Employee employeeToAdd = new Employee();
employeeToAdd.setfName(firstName);
employeeToAdd.setlName(lastName);
employeeToAdd.setAge(empAge);
employeeToAdd.setDepartment(empDep);
//test input and variable setting
System.out.println("--------Inputs------");
varTester(firstName,lastName,empAge,empDep);
System.out.println("--------Recorded Vals------");
varTester(employeeToAdd.getfName(), employeeToAdd.getlName(),employeeToAdd.getAge(),employeeToAdd.getDepartment());
public static void varTester(String empfName, String emplName, int empAge, String empDep){
System.out.println(empfName);
System.out.println(emplName);
System.out.println(empAge);
System.out.println(empDep);
}
}
This is the output from the test method varTester():
--------Inputs------
Somefirstname
Somelastname
32
Accounting
--------Recorded Vals------
Somefirstname
Somelastname
0
null
I test the values received from the showInputDialog's and it is the correct values I want to store int the class instance fields of employeeToAdd though only the first and last name values are set and not the age or department. Can someone point me in the right direction. Thank you.
You got the setter backwards. It should be :
public void setAge(int num){
age = num;
}
You have the same error in setDepartment.
You are supposed to assign to the member variable, not to the argument of the setter method.
Your setter sets the argument not the private field.
public void setAge(int num){
num = age;
}
public void setDepartment(String dep){
dep = department;
}
Change it to:
public void setAge(int num){
age = num;
}
public void setDepartment(String dep){
department = dep;
}
It should be:
public void setAge(int num){
age = num;
}
public void setDepartment(String dep){
department = dep;
}
I have a class named Person.This class represents (as the name says) a Person. Now I have to create a class PhoneBook to represent a list of Persons. How can I do this? I don't understand what means "create a class to represent a list".
import java.util.*;
public class Person {
private String surname;
private String name;
private String title;
private String mail_addr;
private String company;
private String position;
private int homephone;
private int officephone;
private int cellphone;
private Collection<OtherPhoneBook> otherphonebooklist;
public Person(String surname,String name,String title,String mail_addr,String company,String position){
this.surname=surname;
this.name=name;
this.title=title;
this.mail_addr=mail_addr;
this.company=company;
this.position=position;
otherphonebooklist=new ArrayList<OtherPhoneBook>();
}
public String getSurname(){
return surname;
}
public String getName(){
return name;
}
public String getTitle(){
return title;
}
public String getMailAddr(){
return company;
}
public String getCompany(){
return position;
}
public void setHomePhone(int hp){
homephone=hp;
}
public void setOfficePhone(int op){
officephone=op;
}
public void setCellPhone(int cp){
cellphone=cp;
}
public int getHomePhone(){
return homephone;
}
public int getOfficePhone(){
return officephone;
}
public int getCellPhone(){
return cellphone;
}
public Collection<OtherPhoneBook> getOtherPhoneBook(){
return otherphonebooklist;
}
public String toString(){
String temp="";
temp+="\nSurname: "+surname;
temp+="\nName: "+name;
temp+="\nTitle: "+title;
temp+="\nMail Address: "+mail_addr;
temp+="\nCompany: "+company;
temp+="\nPosition: "+position;
return temp;
}
}
Your PhoneBook class will likely have a member like this:
private List<Person> book = new ArrayList<Person>();
And methods for adding and retrieving Person objects to/from this list:
public void add(final Person person) {
this.book.add(person);
}
public Person get(final Person person) {
int ind = this.book.indexOf(person);
return (ind != -1) ? this.book.get(ind) : null;
}
Note that a List isn't the best possible representation for a phone book, because (in the worst case) you'll need to traverse the entire list to look up a number.
There are many improvements/enhancements you could make. This should get you started.
Based on the class being named PhoneBook, I assume that you ultimately want to create a mapping between a phone number, and a person. If this is what you need to do then your PhoneBook class should contain a Map instead of a List (but this may depend on other parameters of the project).
public class PhoneBook
{
private Map<String,Person> people = new HashMap<String,Person>();
public void addPerson(String phoneNumber, Person person)
{
people.put(phoneNumber,person);
}
public void getPerson(String phoneNumber)
{
return people.get(phoneNumber);
}
}
In the above, the phone number is represented as a String, which is probably not ideal since the same phone number could have different String representations (different spacing, or dashes, etc). Ideally the Map key would be a PhoneNumber class that takes this all into account in its hashCode and equals functions.
you can do it by creating a class PhoneBook
public class PhoneBook{
Private List<Person> personList = new ArrayList<Person>;
public void addPerson(Person person){
this.personList.add(person);
}
public List getPersonList(){
return this.personList;
}
public Person getPersonByIndex(int index){
return this.personList.get(index);
}
}