What's wrong with having main class not as a superclass? - java

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.

Related

How to print the data values of an object?

I have created a class employee in Java, where each object of the class stands for a staff. The objects take 3 parameters - Name, Dept. and Salary. The program looks like this:
public class employee
{
String name;
int salary;
String dept;
employee staff1 = new employee("x","IT",100000);
employee staff2 = new employee("y", "HR", 200000);
public employee(String n, String d, int s)
{
this.name= n;
this.salary= s;
this.dept = d;
}
public static void main (String args [])
{
}
public void Display()
{
}
}
I want to make a method (the Display method in the code) which takes the object name as a parameter (the code does not have a parameter) and returns (or prints) its data values. Please also tell me what should come in the main method. Thanks in advance.
You can use this -
public class employee {
String name;
int salary;
String dept;
public employee(String n, String d, int s) {
this.name = n;
this.salary = s;
this.dept = d;
}
public static void main(String args[]) {
employee staff1 = new employee("x", "IT", 100000);
employee staff2 = new employee("y", "HR", 200000);
Display(staff1);
Display(staff2);
}
public static void Display(employee object) {
System.out.println("name='" + object.name + '\'' +
", salary=" + object.salary +
", dept='" + object.dept + '\'');
}
}

How to print an ArrayList? - java

Question will be below.
public class University {
ArrayList<Student> students;
public University() {
students = new ArrayList<Student>();
}
public void addStudent(Student students) {
this.students.add(students);
}}
public class Student {
String name;
String studentID;
static int studentNumber = 0;
Student(String name, String sID){
this.name = name;
this.studentID = sID;
studentNumber++;
}}
public class TestUniversity {
public static void main(String[] args) {
University universityRegister = new University();
Student studentRegister = new Student("Rachel Green", "a1234");
universityRegister.addStudent(studentRegister);
studentRegister = new Student("Monica Geller", "a12345");
universityRegister.addStudent(studentRegister);
studentRegister = new Student("Ross Geller", "a1111");
universityRegister.addStudent(studentRegister);
System.out.println("Number of student in University: " + Student.studentNumber);
}}
A. I created 3 classes, 1.Student, 2.University, 3.UniversityTester, in 3 different files.
B. I created 3 objects of type Studnet, and stored them in the University class as an ArrayList.
I would like to know how I can print the ArrayList of the students including all information from the UniversityTester class? In the future, I will create another object called Stuff and I will store it in the University class as an ArrayList stuffList. Therefore, I don't want to print the students list from class Student.
Override toString() method in Student class as follows:
import java.util.StringJoiner;
public class Student {
String name;
String studentID;
static int studentNumber = 0;
Student(String name, String sID) {
this.name = name;
this.studentID = sID;
studentNumber++;
}
#Override
public String toString() {
return new StringJoiner(", ", Student.class.getSimpleName() + "[", "]")
.add("name='" + name + "'")
.add("studentID='" + studentID + "'")
.toString();
}
}
Now you can print the array list as follows in TestUniversity:
System.out.println("Student Details: " + universityRegister.students);
Add this to your student class:
#Override
public String toString() {
return String.format("Student: %s , StudentID: %s", name, studentID);
}
And then you can print the entire array like this:
System.out.println("Students: " universityRegister.students);
//Or like this:
for(Student st: universityRegister.students){
System.out.println(st);
}

Can't access a variable from another class in Java?

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.

Reference of a non static variable

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.

Java Inheritance of Classes

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.

Categories

Resources