The constructor Teacher(Teacher) is undefined - java

I am using a copy constructor and Inheritance in a class called 'Department' to call the information from class 'Teacher' which is a sub-class of 'Person'. After creating my set/get methods, I get the above error. Anyone have any insight as to why this is occurring?
Code from 'Department' class:
public class Department {
private String deptName;
private int numMajors;
private Teacher[] listTeachers; //inherits from Person class
private Student[] listStudents; //inherits from Person class
// First constructor for Department
public Department(String dn, int nm, Teacher[] listTeachers, Student[] listStudents) {
this.deptName = dn;
this.numMajors = nm;
this.listTeachers = new Teacher[listTeachers.length];
for (int i = 0; i < this.listTeachers.length; i++)
{
this.listTeachers[i] = new Teacher (listTeachers[i]);
}
//set method for Teachers Array
public void setListTeachers (Teacher[] other) {
this.listTeachers = new Teacher[other.length];
for (int i = 0; i < listTeachers.length; i++) {
this.listTeachers[i] = new Teacher (other[i]);
}
}
//get method for Teachers Array
public Teacher[] getListTeachers() {
Teacher[] copyTeachers = new Teacher[listTeachers.length];
for (int i = 0; i < copyTeachers.length; i++) {
copyTeachers[i] = new Teacher(this.listTeachers[i]);
}
return copyTeachers;
}
Here are the lines giving me errors:
1) this.listTeachers[i] = new Teacher (listTeachers[i]);
2) this.listTeachers[i] = new Teacher (other[i]);
3) copyTeachers[i] = new Teacher(this.listTeachers[i]);
Code from 'Teacher' class:
public class Teacher extends Person {
private String id;
private int salary;
private int num_yr_prof;
//Constructor for use in Teacher main method.
public Teacher(String n, int a, String s, boolean al, String i, int sal, int numyr) {
super(n, a, s, al);
this.id = i;
this.salary = sal;
this.num_yr_prof = numyr;
}
//Copy constructor for use in Department class.
public Teacher (String n, int a, String s, boolean al, Teacher other) {
super(n, a, s, al);
if (other == null) {
System.out.println("Fatal Error!");
System.exit(0);
}
this.id = other.id;
this.salary = other.salary;
this.num_yr_prof = other.num_yr_prof;
}

Your copy constructor might look like this:
public Teacher(Teacher teacher) {
this( teacher.n, teacher.a, teacher.s, teacher.al,
teacher.id, teacher.salary, teacher.num_yr_prof );
}
Since you do not show the code for the Person class, I have used the variable names n, a, s, and al here. They should be replaced by whatever those variables are named in the Person class. This, of course, assumes that those variables are either public or protected. If they are private, you need to use the getters for those variables (preferred even if they are public or protected).

You need to to your Teacher class a constructor that accepts a Teacher:
public Teacher(Teacher teacher) {
// do something
}

Related

How do I print out an array list containing both the name of a student and the id of a student?

public class pro1{
static ArrayList <String> student = new ArrayList<String>();
static ArrayList <Integer> id = new ArrayList<Integer>();
String name;
int ID;
public pro1() {
this.name = "";
this.ID = 0;
}
public pro1(String name, int ID) {
this.name = name;
this.ID = ID;
}
public boolean addStudent(String name, int ID) {
student.add(name);
id.add(ID);
return true;
}
/*#Override
public String toString() {
return name + ID;
}*/
public static void main(String args[]) {
pro1 stu = new pro1();
stu.addStudent("john", 1);
stu.addStudent("johnny", 2);
System.out.println(stu);
}
}
I want to print out both the name of the student and the student id using ArrayList. however, I'm not sure how to do that since in this class I can only print out the ArrayList of names or the ArrayList of id. I'm thinking of maybe using another class to create a student object, but I'm not sure how to do so.
great question, I think the best solution for this would be to create a Student object just like you thought!
public static class Student {
private final String name;
private final int id;
public Student(String name, int id) {
this.name = name;
this.id = id;
}
#Override
public String toString() {
return String.format("name=%s, id=%s", name, id);
}
}
public static class School {
private final List<Student> students;
public School(List<Student> students) {
this.students = students;
}
public void add(Student student) {
students.add(student);
}
public List<Student> getStudents() {
return students;
}
}
public static void main(String... args) {
School school = new School(new ArrayList<>());
school.add(new Student("jason", 1));
school.add(new Student("jonny", 2));
school.getStudents().forEach(System.out::println);
}
Non-OOP
Loop the pair of lists.
First sanity-check: Are the two lists the same size?
if( students.size() != ids.size() ) { … Houston, we have a problem }
Then loop. Use one index number to pull from both lists.
for( int index = 0 ;
index < students.size() ;
index ++
)
{
System.out.println(
students.get( index ) +
" | " +
ids.get( index )
) ;
}
OOP
The object-oriented approach would be to define a class. The class would have two member fields, the name and the id of the particular student.
Then create a method that outputs a String with your desired output.
All this has been covered many times on Stack Overflow. So search to learn more. For example: Creating simple Student class and How to override toString() properly in Java?
Uncomment and modify your toString() method as below. It will print both student and id.
#Override
public String toString() {
return student.toString() + id.toString();
}
If you want to have Student to Id mapping, best is to have them in Map collection. Id as key and student name as value.

Calling a constructor with object array

I need to create an object array and read the values of the elements in the constructor from console. I am totally confused how to do it.Can anyone give a clarity about how to do it
public class Student {
int id;
String name;
double marks;
public Student(int id, String name, double marks) {
id = this.id;
name = this.name;
marks = this.marks;
}
}
public class Solution {
public static void main(String[],args)
{
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
Student[] arr=new Student[n];
for(int i=0;i<n;i++)
{
int x =sc.nextInt();
String y=sc.nextLine();
double z=sc.nextDouble();
arr[i]=arr.Student(x,y,z);
}
}
}
I am confused on how to call the constructor.
Can anyone help me?
You can do one of two things:
1.Create a temporary object by calling the constructor and then adding that object in the array:
Student temp= new Student(x,y,z);
arr[i]=temp;
2.Directly instantiate a new object and add it in the array like this:
arr[i]=new Student(x,y,z);
Both methods will work fine, but it is recommended to use method 2 because you should not allocate memory to a temp object when clearly you can achieve the goals without doing so
Instead of:
arr[i]=arr.Student(x,y,z);
Do:
arr[i]=new Student(x,y,z);
Why? Because, Each object in the array is an instance of Student class
Your constructor is declared wrongly. this is always used to refer to the instance variable. Change your constructor to this:
public class Student {
int id;
String name;
double marks;
public Student(int id, String name, double marks) {
this.id = id;
this.name = name;
this.marks = marks;
} }
public class Solution {
public static void main(String[],args)
{
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
Student[] arr=new Student[n];
for(int i=0;i<n;i++)
{
int x =sc.nextInt();
String y=sc.nextLine();
double z=sc.nextDouble();
arr[i]= new Student(x,y,z); //no need to create an object for arr
}
}
}
Because your constructor is wrong.
public class Student {
int id;
String name;
double marks;
public Student(int id, String name, double marks) {
this.id = id;
this.name = name;
this.marks = marks;
}
}

Add objects with random variables using a loop

I am trying to write a program where I ask to the user how many persons he wants to implement in this world. Afterwards, I would like as many person objects as the user answered. I defined a person class with a person constructor containing all person variables ( + getters/setters). After this, I tried to create a loop to assign values to my variables (most of them happen random). Currently, I set the number of instances I want to create to 20 (arbitrary).
This is my person class
public class Person implements Item {
public static final int MAX_AGE = 70;
public static final int MAX_SEX_APPEAL = 10;
public static final int MAX_AGRESSION_LEVEL = 10;
public static final int MAX_STRENGTH = 10;
private int id;
private int age;
private boolean gender;
private int sexAppeal;
private int agressionLevel;
private int strength;
private boolean isAlive;
public Person (int id, int age, boolean gender, int sexAppeal, int agressionLevel, int strength, boolean isAlive){
this.setId(id);
this.setAge(age);
this.setGender(gender);
this.setSexAppeal(sexAppeal);
this.setAgressionLevel(agressionLevel);
this.setStrength(strength);
this.setAlive(isAlive);
}
void getBorn () {
isAlive = true;
age = 0;
// a new people is born
// age = 0
// other variables: random
}
void die () {
isAlive = false;
// people die when they reach the max age
// people die when being on the same cell as vulcanos
// people can be murdered
// setAlive = false
}
void murder () {
// when 2 people with min agression level on the same land ==> weakest one dies
}
void move () {
// method to make people move
// random (only to adjucant fields)
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isGender() {
return gender;
}
public void setGender(boolean gender) {
this.gender = gender;
}
public int getSexAppeal() {
return sexAppeal;
}
public void setSexAppeal(int sexAppeal) {
this.sexAppeal = sexAppeal;
}
public int getAgressionLevel() {
return agressionLevel;
}
public void setAgressionLevel(int agressionLevel) {
this.agressionLevel = agressionLevel;
}
public int getStrength() {
return strength;
}
public void setStrength(int strength) {
this.strength = strength;
}
public boolean isAlive() {
return isAlive;
}
public void setAlive(boolean isAlive) {
this.isAlive = isAlive;
}
}
And this is my "test class" where I try to create 20 instances :
import java.util.concurrent.ThreadLocalRandom;
public class test {
public static void main(String[] args) {
for (int i = 0; i < 20; i ++) {
Person person(i) = new Person();
person.setId(i);
person.setAge(ThreadLocalRandom.current().nextInt(0, Person.MAX_AGE + 1));
person.setGender((Math.random() < 0.5));
person.setSexAppeal(ThreadLocalRandom.current().nextInt(0, Person.MAX_SEX_APPEAL + 1));
person.setAgressionLevel(ThreadLocalRandom.current().nextInt(0, Person.MAX_SEX_APPEAL + 1));
person.setStrength(ThreadLocalRandom.current().nextInt(0, Person.MAX_SEX_APPEAL + 1));
person.setAlive(true);
}
}
}
However, I am getting the following error at this line
Person person(i) = new Person();
The constructor Person () is undefined
Type mismatch: cannot convert from Person to int
I understand those errors but I don't know another way to become to the result I want to achieve
You should make a list and just add the created persons to it.
public class test {
public static void main(String[] args) {
List<Person> persons = new ArrayList<>(); // create a list to store the generated persons
for (int i = 0; i < 20; i++) {
Person person = new Person(); // generate a person
person.setId(i);
person.setAge(ThreadLocalRandom.current().nextInt(0, Person.MAX_AGE + 1));
person.setGender((Math.random() < 0.5));
person.setSexAppeal(ThreadLocalRandom.current().nextInt(0, Person.MAX_SEX_APPEAL + 1));
person.setAgressionLevel(ThreadLocalRandom.current().nextInt(0, Person.MAX_SEX_APPEAL + 1));
person.setStrength(ThreadLocalRandom.current().nextInt(0, Person.MAX_SEX_APPEAL + 1));
person.setAlive(true);
persons.add(person); /// add the generated person to the list
}
}
}
Also if you want to call the Person constructor without parameters the class must have a constructor that takes no parameters.
public Person() {}

JAVA Null pointer Exception getTitle method, I can't find it

There's no error while coding it, but when i ran it, it said
Exception in thread "main" java.lang.NullPointerException
at homework.Book.getTitle(Book.java:36)
at homework.BookMain.main(BookMain.java:61)
Java Result: 1
***********************************
package homework;
public class BookMain {
public static void main(String[] args){
int i;
int option;
Book[] bookSet = new Book[20];
bookSet[0] = new Book("I dare you","Joyce Meyer",2007);
bookSet[1] = new Book("Straight from the Heart","Rev. Fr. Mario Jose C. Ladra",2012);
bookSet[2] = new Book("Deliverance From Fear","Bob Buess",1993);
bookSet[3] = new Book("Extraordinary Book of Facts","Bathroom Readers' Institute",2006);
bookSet[4] = new Book("Fat Kid Rules the World","K.L. Going",2003);
Book.numberOfBooks = 5;
Book getter = new Book();
for (i=0; i<Book.numberOfBooks; i++)
{
System.out.println(getter.getTitle(bookSet[i])+" "+getter.getAuthor(bookSet[i])+" "+getter.getYear(bookSet[i]));
}
System.out.println();
for (i=0; i<Book.numberOfBooks; i++)
{
if(getter.getYear(bookSet[i])>2000)
System.out.println(getter.getTitle(bookSet[i])+" "+getter.getAuthor(bookSet[i])+" "+getter.getYear(bookSet[i]));
}
bookSet[5] = new Book("The Lake of Dead Languages","Carol Goodman",2002);
Shelf shelf1 = new Shelf("Shelf1","Bedroom");
Shelf shelf2 = new Shelf("Shelf2","Living room");
Shelf shelf3 = new Shelf("Shelf3","Basement");
Shelf placer = new Shelf();
placer.insertBook(shelf1,bookSet[1]);
placer.insertBook(shelf1,bookSet[2]);
placer.insertBook(shelf2,bookSet[3]);
placer.insertBook(shelf2,bookSet[4]);
placer.insertBook(shelf1,bookSet[5]);
placer.insertBook(shelf1,bookSet[0]);
System.out.println(placer.getShelfName(shelf1)+" "+placer.getLocation(shelf1));
Book aBookInShelf = new Book();
for(i=0; i<shelf1.booksInShelf; i++)
{
aBookInShelf = placer.pickBook(shelf1, i);
System.out.println(getter.getTitle(aBookInShelf)+" "+getter.getAuthor(aBookInShelf)
+" "+getter.getYear(aBookInShelf));
}
}
}
===========================================
Books class:
package homework;
public class Book {
private String title;
private String author;
private int year;
public static int numberOfBooks = 0;
public Book(String title, String author, int year){
this.title=title;
this.author=author;
this.year=year;
}
public Book(){
}
public String getAuthor(Book target){
return target.author;
}
public int getYear(Book target){
return target.year;
}
public String getTitle(Book target){
return target.title;
}
public static void main(String[] args){
}
}
=====================================
Shelves class:
package homework;
public class Shelf {
private String name;
private String location;
public static int booksInShelf=0;
private Book[] shelfBooks = new Book[20];
public Shelf(String name, String location){
this.name = name;
this.location = location;
}
public Shelf(){
}
public String getShelfName(Shelf target){
return target.name;
}
public String getLocation(Shelf target){
return target.location;
}
public void insertBook(Shelf target, Book aBook){
target.shelfBooks[target.booksInShelf] = aBook;
target.booksInShelf++;
}
public Book pickBook(Shelf target, int nthBook){
return target.shelfBooks[nthBook];
}
}
Beside getter/setter design madness it seems that NullPointerException is caused by fact that booksInShelf is static, which means that it belongs to entire Shelf class (instances of this class share value of this field) so when you add book to one Shelf and increment this field, it will be incremented for all instances of Shelf.
Because of that in loop
for(i=0; i<shelf1.booksInShelf; i++)
you are iterating even over positions that were not set yet and are still nulls. Now in
aBookInShelf = placer.pickBook(shelf1, i);
System.out.println(getter.getTitle(aBookInShelf)+" "+getter.getAuthor(aBookInShelf)
+" "+getter.getYear(aBookInShelf));
you are picking this null and using it inside getter.getTitle(null) which will try to invoke return null.title which will case NPE because null doesn't have title.
To fix this problem remove static modifier from booksInShelf field.

Java Subclasses last instance overwriting values

I'm a web developer dabbling in Java (again) and I'm having trouble with something.
Basically, I have a superclass Employee with two subclasses that extend it called Management and Programmer. The Employee class contains an array employees that is basically an array of Employee objects.
Here's the important snippets of two of the classes (Employee and Management) and the final main method. I'll explain the output at the bottom.
public class **Employee** {
private static String firstName;
protected static int MAXEMPLOYEES = 5;
protected Employee[] employees = new Employee[MAXEMPLOYEES];
protected int totEmployees = 0;
public Employee(String first) {
setFirstName(first);
}
public void setFirstName(String str){
firstName = str;
}
public String getFirstName(){
return firstName;
}
public boolean addEmployee(String fname) {
boolean added = false;
if (totEmployees < MAXEMPLOYEES) {
Employee empl = new Employee(fname);
employees[totEmployees] = empl;
added = true;
totEmployees++;
}
return added;
}
}
public class **Management** extends **Employee** {
private String title = "Project Manager";
public Management(String fname, String t){
super(fname);
title = t;
}
public boolean addManagement(String fname, String t){
boolean added = false;
if (totEmployees < MAXEMPLOYEES) {
employees[totEmployees] = new Management(fname, t);
added = true;
totEmployees++;
}
return added;
}
}
-------------------------------------
package employee;
public class EmployeeApplication {
public static void main(String[] args) {
Employee[] empl = new Employee[3];
empl[0] = new Employee("Kyle");
empl[1] = new Management("Sheree", "Director");
System.out.println(empl[0].getFirstName());
}
}
Now, I expect the system to print out "Kyle", but it prints out "Sheree". Any ideas???
private static String firstName;
You made firstName static, which means all instances share the same name. You'll need to remove the static modifier in order for different Employees to have different names. You'll also need to change the private access modifier to protected in order for the field to be inherited by subclasses.
private String firstName;
remove static;
Kyle was overridden by Sheree, that is why you are getting that output

Categories