Can anyone help me with "tostring" method in java? - java

Im doing an OOP assignment.. It has four classes Person, student and employee both extends person and instructor that extends employee. .
I have done Almost everything i could but i cant print out values using tostring method and Cant fill the array.I have used getter setter and all the constructor and methods are there still cant get any output. heres the person class and all the remain three classes have been made. plus the main file
abstract class Person
{
protected int Id;//"protected"Only child can use this
protected String Name;
public Person() {}
public Person(int id,String name)
{
this.Id=id;
this.Name=name;
}
public int getId()
{
return this.Id;
}
public void setId(int id)
{
this.Id=id;
}
public String getName()
{
return Name;
}
public void setName(String name)
{
this.Name=name;
}
public String toString()
{
return Id + Name + " is a student ";
}
public static int getMaxID()
{
return 0;
}
////////////////////////////////////////////////////////////////////////////////
public class Employee extends Person
{
protected double Salary;
protected String employeeName;
public Employee() {}
public Employee(double salary)
{
this.Salary=salary;
}
public Employee(String employeename)
{
this.employeeName=employeename;
}
public String getemployeeName()
{
return employeeName;
}
public void setemployeeName(String employeename)
{
this.employeeName=employeename;
}
public double getSalary()
{
return this.Salary;
}
public void setSalary(double salary)
{
this.Salary=salary;
}
public String toString()
{
return employeeName + " is an instructor earning a salary of " + Salary;
}
}
////////////////////////////////////////////////////////////////////////////////
public class Student extends Person
{
protected int teacherID;
protected String teacherName;
protected String studentName;
public Student() {}
public Student(int teacherid,String teachername)
{
this.teacherID=teacherid;
this.teacherName=teachername;
}
public Student(String studentname)
{
this.studentName=studentname;
}
public Student(String teachername, String studentname, Person[] person_array)
{
this.teacherName=teachername;
this.studentName=studentname;
}
public int getteacherID()
{
return this.teacherID;
}
public void setteacherID(int teacherid)
{
this.teacherID=teacherid;
}
public String getteacherName()
{
return teacherName;
}
public void setteacherName(String teachername)
{
this.teacherName=teachername;
}
public String toString()
{
return studentName + " is a student ";
}
}
////////////////////////////////////////////////////////////////////////////////
public class Instructor extends Employee
{
int[] studentID=new int[10];
protected String instructorName;
public Instructor(String instructorname)
{
this.instructorName=instructorname;
}
public Instructor(String instructorname, double salary)
{
this.instructorName=instructorname;
this.Salary=salary;
}
public double getSalary()
{
return Salary;
}
public void setSalary(int salary)
{
this.Salary=salary;
}
public String getinstructorName()
{
return instructorName;
}
public void setinstructorName(String instructorname)
{
this.instructorName=instructorname;
}
static void findStudents(Person[] person_array)
{
}
public String toString()
{
return instructorName + " is an instructor earning a salary of " + Salary;
}
}
////////////////////////////////////////////////////////////////////////////////
//CIS 459.23 Lab 2
//Due Oct 30 (Sunday)
//OSU wants you write some classes for their Personnel Record System. To make it simple,
//consider only 4 classes: Person, Employee, Instructor and Student. The following figure
//illustrates the relationship between these 4 classes. The Person class is the parent class of the
//Employee class and the Student class. The Employee class is the parent class of the Instructor
//class.
//The following are the tasks you need to complete for each of these classes.
// Create appropriate fields for each class. Necessary fields are listed. Add your own fields if
//needed. Some fields need to have appropriate constraint. Use your own way to make sure
//that these constraints are satisfied.
//o Person
//ID: int, starting from 1 and should be unique
//Name: String
//o Employee
//Salary: double and should not be negative
//o Student (For simplicity, assume that a student has at most 1 teacher)
//TeacherID: int. It’s his/her instructor's ID. 0 if no instructor is given
//TeacherName: String
//o Instructor:
// StudentIDArray: int array. An array of students’ IDs of this instructor. Set the
// array size to be 10, initially all 0s, assuming an instructor won’t have more than
// 10 students.
// All the above fields are private and only accessible through the access methods.
// A “toString()” method for each class to print out all the available information about the
// current object. In Person class “toString()” is declared as abstract.
// A static “findStudents(Person[] personArray)” method in the Instructor class to fill an
// instructor object’s students ID array, and the corresponding students’ TeacherID fields. See
// the test program for better understanding.
// Person should be declared as abstract class.
// Provide multiple constructors/methods if needed. Check the test.java program to see what
// constructors/methods are necessary and what actions they should do.
// If a class can use the parent class method and constructor, use “super” to call it to reduce the
// redundant code.
// Make sure this test.java program can work with your class.
// sample output. From this sample output, you’ll know what information you should print out
// for a specific object.
// NOTE: the sample output is not the unique output format of the test program. The real output
// format depends on how you design the toString() methods in each class. But make sure that your
// program will print out as much information about each object’s fields as possible, including the
// Person
// Instructor
// Employee Student
// inherited fields and the fields defined in its own class.
// HINT:
// o There is NO main method in any of these 4 classes
// o To make sure ID is unique across the objects, declare a static “LAST_ID” in the Person
// class.
// o Read descriptions in test.java VERY CAREFULLY for better
// understanding!
// Submit your Person.java, Emloyee.java, Student.java and Instructor.java files
// Appendix 1: Test Program
/*
* Lab 2 Program to test the Person, Employee, Student, and Instructor classes.
*/
public class Lab2_Test
{
public static void main(String[ ] args)
{
// uncommenting the following line should produce a compile error.
// This is for testing of an abstract class.
// Person p = new Person("George");
final int MAX_HEADCOUNT = 20;
Person[] person_array = new Person[MAX_HEADCOUNT];
// A student named Peter
person_array[0] = new Student("Peter");
// An instructor named Peter
person_array[1] = new Instructor("Peter");
// An instructor named Sandy and her salary
person_array[2] = new Instructor("Sandy", 25000);
// A janitor named Bob
person_array[3] = new Employee("Janitor Bob");
// A student named Tom and his instructor is Peter.
// The constructor needs to do three things:
// 1: sets this student’s “TeacherName” field to be “Peter”,
// 2: finds out the ID of the 1st instructor
// who exists in the person_array so far and named "Peter",
// and assign it to this student's “TeacherID” field.
// Set it to be 0 if no instructor named Peter is found in the person_array so far
// 3: records this student’s ID in the instructor’s StudentArray if such an instructor is found
// right after executing the following statement
// person_array[4].TeacherID = 2
// person_array[4].TeacherName = “Peter”
// person_array[1].StudentArray[0] = 5
person_array[4] = new Student("Tom", "Peter", person_array);
// A student named Maggie and her instructor is Susan
// right after executing the following statement
// person_array[5].TeacherID = 0
// person_array[5].TeacherName = “Susan”
person_array[5] = new Student("Maggie", "Susan", person_array);
// An instructor named Susan and her salary
person_array[6] = new Instructor("Susan", 40000);
// After all objects are created,
// instructors need to fill their students arrays,
// and some students need to fill their TeacherIDs now,
// since there may exist cases that when a Student object is created with instructor’s name,
// the corresponding Instructor object hasn’t been created and is not in the person_array.
// For example, person_array[6] is created after person_array[5].
// You need to record person_array[5]’s ID in person_array[6]’s studentArray field,
// and record person_array[6]’s ID in person_array[5]’s TeacherID field.
// Note: if there are more than one Instructor objects
// having the same names as a Student object’s TeacherName,
// it’ll always be the first one’s ID assigned to the Student object’s TeacherID
Instructor.findStudents(person_array);
System.out.println("ID and name of all personnel in the array");
for (int i = 0; i < Person.getMaxID(); i++)
{
System.out.println(person_array[i].getId() + ":" + person_array[i].toString());
}
}

You are trying to print using this:
for (int i = 0; i < Person.getMaxID(); i++)
{
System.out.println(person_array[i].getId() + ":" + person_array[i].toString());
}
But, the getMaxID() method in your Person class returns a hardcoded 0, so this loop will never iterate, and your print statement will never be reached.
EDIT: it makes no sense to even check for a maxId. Check against the length of the array:
for (int i = 0; i < person_array.length; i++)
{
System.out.println(person_array[i].getId() + ":" + person_array[i].toString());
}

Related

How to add a user-defined data type into a set?

this is my mock test from my professor and I having trouble writing it in Java.
This is the question:
An ADT to manage a collection of students in a course is required. You
can assume that there are no more than 100 students in any course. A
student's record consists of ID (String), name (String), and GPA
(double). There is no duplication in student IDs, but it is possible
to have two or more students with the same name and/or GPA.
Create a new type StudentCollection (it is equivalent to a class in
Java). Except for the constructor, your StudentCollection type must
support the following 3 public operations (feel free to add additional
private operations as needed - but their scope have to be private)
void addStudent(Student std): add a new student std to your
collection. If there is a student having the same ID as std in your
collection already, do nothing.
Student searchByName(String name): search the student collection and
return any student whose name contains name completely (case
sensitive). Examples: "ABC" contains "ABC" completely; "ABC" contains
"A" completely; "ABC" contains "C" completely, "ABC DEF" contains "C
D" completely; "ABC" does NOT contain "CB" completely; "ABC" does NOT
contain "abc" completely. If there is more than one matching student,
your method can return any student. If there is no matching student,
return null. int rankStudent(String sID): return the rank of a student
whose ID is sID with regard to this collection. The ranking is done
using students' GPAs. A student with the highest GPA has a rank of 1.
In this example, let assume there are 4 GPA values [9.0, 8.5, 7.0,
8.5]. A student whose GPA = 9.0 has a rank of 1, a student whose GPA = 8.5 has a rank of 2 (there are 2 students who have the same rank of 2), and a student whose GPA = 7.0 has a rank of 4. If there is no
student found with the provided sID, return -1.
Create a StudentCollection object and use it in the main method
(client code). Your client code must call all the above 3 public
methods one or more times.
You are NOT allowed to use the Java Collection Framework classes for
this problem. Your code for this problem must be stored in a single
file StudentCollection.java.
The ADT I'm choosing here is Set. Since the instruction doesn't allow me to use the Java Collection Framework, I have to manually implement all of the functions.
But here is the problem:
for the first function, the question ask me to write void addStudent(Student std) which when implementing a Set ADT, I cannot pass in a user defined data type Student into the function, I have done some research and we have to pass in a Set parameter instead of a user defined data type. Here is the code for class Student:
static class Student {
private String ID;
private String name;
private double GPA;
Student(String ID, String name, double GPA) {
this.ID = ID;
this.name = name;
this.GPA = GPA;
}
}
let's say that we put in the Student class, then there have to be some getters and setters inside of the Student class. But the question limit the amount of public function to implement and all functions beside the three specify function above have to be private. How can a getter and setter be private? Is it possible?
The overall question is: How to add a user-defined data type into a set?
I'm sorry if there is any explanation of mine is not clear. Please reply to this question if you have any further question.
Here is the code that I have been working on:
import java.util.HashSet;
import java.util.Set;
public class StudentCollection {
static Set<Student> manage = new HashSet<>();
static class Student {
private String ID;
private String name;
private double GPA;
Student(String ID, String name, double GPA) {
this.ID = ID;
this.name = name;
this.GPA = GPA;
}
}
public static void addStudent(Student std) {
manage.add(std);
}
// public static Student searchByName(String name) {
//
// }
//
// public static int rankStudent(String sID) {
//
// }
public static void main(String[] args) {
Student std = new Student("s387", "nam", 3.7);
addStudent(std);
}
}
The Student class has to be public, with public getters. Otherwise, you couldn't create a Student instance to add a student.
I went ahead and coded the addStudent method. I'm leaving the rest of the code for you to finish.
You'll have to go over your class notes to verify, but this is how I would start coding the StudentCollection class. There are no static fields or methods, other than the main method.
public class StudentCollection {
public static void main(String[] args) {
StudentCollection sc = new StudentCollection();
sc.addStudent(sc.new Student("10001", "George", 9.0));
}
private int studentLength;
private Student[] students;
public StudentCollection() {
this.studentLength = 0;
this.students = new Student[100];
}
public void addStudent(Student student) {
for (int index = 0; index < studentLength; index++) {
if (student.getSID().equals(students[index].getSID())) {
return;
}
}
students[studentLength++] = student;
}
public Student searchByName(String name) {
}
public int rankStudent(String sID) {
}
public class Student {
private final double gpa;
private final String sID, name;
public Student(String sID, String name, double gpa) {
this.sID = sID;
this.name = name;
this.gpa = gpa;
}
public double getGpa() {
return gpa;
}
public String getSID() {
return sID;
}
public String getName() {
return name;
}
}
}

Constructor printing out NULL instead of object value

I created a new class "Lecturer" which extends another class "Person", i wanted to make 2 constructors for Lecturer and one would accept a name and a stipend (just a constant to say how much pay is), the other just accepts the name and uses the default stipend set in the code. i included appropriate getters and setters. I then wrote a writeOutput method to print an output similar to this
Name: (name) which gets the name and prints it
Stipend: (stipend) same process ^
heres what i have so far
Lecturer.java
public class Lecturer extends Person{
private static String name;
static double stipend;
public Lecturer(String name) {
super(name);
}
public Lecturer(String name, double stipend) {
super(name);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getStipend() {
return stipend;
}
public void setStipend(double stipend) {
this.stipend = stipend;
}
public static void writeOutput() {
System.out.println("Name: " + name);
System.out.println("Stipend: " + stipend);
}
}
Person.java
public class Person {
/** Every Person has a name */
private String name;
/** Person requires a name */
public Person(String n) {
this.name = n;
}
/** return this Person's name */
public String getName() {
return this.name;
}
/** Change this Person's name */
public void setName(String nn) {
this.name = nn;
}
Main file (Inheritance.java)
Lines 41-53
Lecturer l1 = new Lecturer("Zachary");
Lecturer l2 = new Lecturer("Wilhelmina", 11017.00);
l1.writeOutput();
l2.writeOutput();
pause();
l1.setName("Zack");
l1.setStipend(10800.00);
l1.writeOutput();
pause();
System.out.printf("%s's stipend is $%,4.2f.\n",
l1.getName(), l1.getStipend());
System.out.printf("%s's stipend is $%,4.2f.\n",
l2.getName(), l2.getStipend());
This is the output
Name: null
Stipend: 0.0
Name: null
Stipend: 0.0
press enter...
Name: Zack
Stipend: 10800.0
The 2nd part works as it should but the first one isnt and i tried to change the code but nothing is working properly.
In Lecturer you are declaring another name variable. This variable is separate from the name variable declared in Person. The call to the superclass constructor is setting the name variable in Person, not in Lecturer. But you don't need the second variable; remove it. You can access the name in Person via the getName method you've already declared. This means that you also don't need to re-declare getName and setName in Lecturer, so the Lecturer class can inherit them.
Also, in Lecturer, the two variables you've declared shouldn't be static. Per the above reasoning, name shouldn't even be there, but even if it should be there, it shouldn't be static. The variable stipend should be there, but it shouldn't be static. When you declare a member variable static, then there is only one variable for the entire class, no matter how many instances you create, which doesn't sound like what you want.
Your constructors should initialize stipend.
You have a static variable inside Lecturer which has the same name as the inherited one from Person and your getter is referring to that static one - are you sure you want these static variables? For completeness if you really want to keep the static one and the inherited one with the same name then change your getter to read return this.name; which will return the inherited name instance variable.... But that method can be inherited from Person class...
There are two name fields in your program , one is private static String name; in Lecturer.java and another is private String name; in person.java .
The thing is that you are just calling Lecturer javs's name field but not setting it.
Fixed the project based on rgettman answer.
Lecturer class should look like this:
public class Lecturer extends Person {
double stipend = 9144;
public Lecturer(String n) {
super(n);
}
public Lecturer(String n, double stipend) {
super(n);
this.stipend = stipend;
}
public double getStipend() {
return stipend;
}
public void setStipend(double stipend) {
this.stipend = stipend;
}
public void writeOutput() {
System.out.println("Name: " + this.getName());
System.out.println("Stipend: " + getStipend());
}
}

How to print the int value of an object inside another object array?

How does one print the private int data field of an object that's within another object's array.
So if I had an object called Classroom and another object called Student, how would I print the student ID's of the student objects inside the Classroom object's private array member?
Would I override toString within Student to print the studentID? But how do you use that in the Classroom object's array to print out the array of IDs?
In your Student class, you should create a method that returns the student's id, like in the example below:
class Student
{
private id;
//... constructor and other code
int getID() {return this.id;}
}
In your Classroom class, you should create a method that adds the student to the array of students (I used an ArrayList in this case) and a method that prints the ids of all students in the list. Look below:
class Classroom
{
private ArrayList<Student> studentsList;
//... constructor and other code
void addStudent(Student student) {
this.studentsList.add(student);
}
void printStudentsList() {
for(Student student: this.studentsList) {
System.out.println(student.getID());
}
}
}
Note that it's just one of the ways you can use to achieve what you want. Since you didn't post your code, I improvised with the information you gave.
class Student{
private ArrayListids;
public Student(){
ids.add("S001");
ids.add("S002");
}
public ArrayList<String> getID(){
return this.ids;
}
}
class ClassRoom {
public static void main(String args[]){
Student s=new Student();
ArrayList<String>studentID=s.getID();
for(String id:studentID){
System.out.println("Student ID :"+id);
}
}
}
I think that you need to create some public methods to use the private attributes. I think you can design Student and Classroom class as following:
class Student
{
private int studentID;
//and others private attributes
public student()
{
//write something here to initiate new object
}
public int getID()
{
return studentID;
}
//you can insert others methods here
}
class Classroom
{
private Student[] studentArray;
//add constructer here if you need it
public int getStudentId(int position) //get student ID at `position` in the array
{
return studentArray[position].getID();
}
}
public class Main
{
public static void main(String[]args)
{
Classroom classroom = new Classroom();
//do something to insert student to array of the `classroom`
//assume you need to get ID of student in 6th place
System.out.println(classroom.getStudentID(6));
}
}

How do I implement these super class methods?

What I'm supposed to do:
write a java program to show the inheritance concept with an Employee being the super class and the Manager being the sub-class. Follow the following class structure: - Employee class
Variables:
Employee Number
Employee Name
Employee Salary
Constructor – Use this to initialize all the variables above Functions
Display() – This displays all the 3 variable values.
setSalary() – This sets the salary variable.
getSalary() – This gets the salary variable.
Heres what I have so far
public class Employee {
private int employeeNumber;
private String employeeName;
private double employeeSalary;
public Employee(int employeeNumber, String employeeName, double employeeSalary) {
this.employeeNumber = employeeNumber;
this.employeeName = employeeName;
this.employeeSalary = employeeSalary;
}
}
My question is how do I implement those three methods?
Are they just standard getters and setters?
I'm not familiar with the display function, if anyone can help with that
thanks!
You are really close. You need to create the manager Class and extend the Employee Class. But first let's add the described method for setting the salary and displaying all the fields!
Employee Class: The display() method concatenates the fields together separating them by line.
public class Employee {
private int employeeNumber;
private String employeeName;
private double employeeSalary;
public Employee(int employeeNumber, String employeeName, double employeeSalary){
this.employeeNumber=employeeNumber;
this.employeeName=employeeName;
this.employeeSalary=employeeSalary;
}
public void display(){
System.out.println("Employee Number: "+ employeeNumber +"\n"
+ "Employee Name: " + employeeName + "\n"
+ "Employee Salary: " + employeeSalary);
}
public double getEmployeeSalary() {
return employeeSalary;
}
public void setEmployeeSalary(double employeeSalary) {
this.employeeSalary = employeeSalary;
}
}
Manager Class: From general knowledge I would assume that a Manager could have multiple employees also.
So in this class you'd have specific methods for the Manager, such as adding a new Employee, or displaying or the Employees who work for a given Manager.
public class Manager extends Employee {
List<Employee> subordinates;
public Manager(int employeeNumber, String employeeName, double employeeSalary) {
super(employeeNumber, employeeName, employeeSalary);
subordinates = new ArrayList<>();
}
public void displayEmployees(){
for(Employee employee: subordinates){
employee.display();
// just print an empty line - so its prettier
System.out.println();
}
}
public void addNewEmployee(Employee employee){
subordinates.add(employee);
}
public List<Employee> getSubordinates() {
return subordinates;
}
public void setSubordinates(List<Employee> subordinates) {
this.subordinates = subordinates;
}
}
Testing: note that a Manager inherits all the methods of the Employee class, which is why within the Manager class there was no need to override the methods, but of course that can be done to add new functionality.
public class Main {
public static void main(String[] args) {
Manager manager = new Manager(11111, "Elon Musk", 42344);
manager.display();
// lets make some employees who work for the above manager
Employee employeeOne = new Employee(324, "Bob Den", 3522);
Employee employeeTwo = new Employee(44, "Tim Pipe", 4234 );
Employee employeeThree = new Employee(42, "Asif Blar", 4321);
// lets add the new employees to the managers list of employees ( this can further be refactored )
manager.addNewEmployee(employeeOne);
manager.addNewEmployee(employeeTwo);
manager.addNewEmployee(employeeThree);
// lets display all the employees who work for the manager
manager.displayEmployees();
// lets give the manager a 10 % raise
double employeeSalary = manager.getEmployeeSalary();
manager.setEmployeeSalary(employeeSalary +(employeeSalary /10));
// lets print out the managers hefty new salary
manager.display();
}
}

Best way to access an object stored in an ArrayList?

I have a Student class that contains an ArrayList of type Course, and Course is class with some fields like className, classTime, etc along with the appropriate getters and setters. Say I created an ArrayList of Course and have stored it into the Student class.
How can I for example print the className of a particular Course object (which is stored in an ArrayList stored in the Student class)?
So far I tried this, below is part of the code for class Student:
class Student {
ArrayList<Course> studentSchedule;
public ArrayList<Course> getStudentSchedule() {
return studentSchedule;
}
public void setStudentSchedule(ArrayList<Course> studentSchedule) {
this.studentSchedule = studentSchedule;
}
}
Then I have some code that created student1 of type Student and stored an ArrayList of Course into it.
Say I want to access the className in the first object in the ArrayList that's in student1. So far I have this and it works... is it fine?
ArrayList<Course> schedule = student1.getStudentSchedule();
System.out.print("\n course name at position 0 is " +
student1.getStudentScheduleClassName(0));
It feels weird to create another Arraylist just for this purpose... but then I thought since in line 1, schedule will only contain the addresses that point to the location and shouldn't take much space?
Is there a more appropriate way to do this?
Based on above discussion I tried to complete the solution for my reference.
import java.util.ArrayList;
import java.util.Iterator;
public class ListExample {
public static void main(String[] args) {
Student student1 = new Student();
ArrayList<Course> student1Schedule = new ArrayList<Course>();
student1Schedule.add(new Course("Computer Science", "Training Room"));
student1Schedule.add(new Course("Mobile App Development", "Training Room 2"));
student1.setStudentSchedule(student1Schedule);
// Prints only one course
System.out.println(" ** Course" + student1.getStudentSchedule().get(0).toString());
// Print all the courses attended by the student
ArrayList<Course> studentDetails = student1.getStudentSchedule();
Iterator<Course> studentIterator = studentDetails.iterator();
while (studentIterator.hasNext()) {
Course courseName = studentIterator.next();
System.out.println(courseName);
}
}
static class Student {
private ArrayList<Course> studentSchedule;
public ArrayList<Course> getStudentSchedule() {
return studentSchedule;
}
public void setStudentSchedule(ArrayList<Course> studentSchedule) {
this.studentSchedule = studentSchedule;
}
}
static class Course {
private String courseName;
private String className;
public Course (String courseName, String className){
this.className =className;
this.courseName = courseName;
}
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String toString (){
return "Course Name :" + this.courseName + "\n" + "Class Name : " + className + "\n";
}
}
}
public class Course{
private String className;
public String getClassName(){
return className;
}
public void setClassName(String c){
className =c;
}
}
So when you have this you can simply do
System.out.println(student1.getStudentSchedule().get(0).getClassName())
Make className into an instance variable of Course and have getter and setter methods within the Course for the class name. Then you will print out the class name.
You can access the first course's class name as:
System.out.print("\n course name at position 0 is " + schedule.get(0).getClassName());
since you've already defined getter/setter in the Course class as you mentioned.

Categories