I am trying to create a constructor for class HthsStudent, where it inherits variables and states from class Student. (Student inherited variables and states from class Person.)
The problem is, java doesn't like the way I'm trying to do it, and keeps telling me that what I'm doing is wrong, even though it is exactly what I did in class Student. It tells me that there is a "invalid method declaration, return type required" error, but I don't see a way to fix it.
What am I doing wrong, and how can I fix it?
Thanks!
/**
* Write a description of class Persn here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class Person
{
String firstName;
String lastName;
public Person (String firstName, String lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
public String toString ()
{
return lastName + ", " + firstName;
}
}
/**
* Write a description of class Student here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class Student extends Person
{
int gradeLevel;
private static int studentId = 0;
public Student (String firstName, String lastName, int gradeLevel)
{
super(firstName, lastName);
this.gradeLevel = gradeLevel;
if (gradeLevel > 5 || gradeLevel < 0)
{
gradeLevel = 0;
}
studentId = studentId + 1;
}
public int getLevel()
{
return gradeLevel;
}
public String toString ()
{
return lastName + ", " + firstName + "\nGrade Level: " + gradeLevel + "\nID #: " + studentId;
}
}
/**
* Write a description of class HTHSStudent here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class HTHSStudent extends Student
{
double gpa;
public HthsStudent (String firstName, String lastName, int gradeLevel, double gpa)
{
super(firstName, LastName, gradeLevel);
this.gpa = gpa;
if (gpa > 5.0 || gpa < 1.0)
{
gpa = 0.0;
}
}
public String toString()
{
return lastName + ", " + firstName + "\nGrade Level: " + gradeLevel + "\nID #: " + studentId + "\nGPA: " + gpa;
}
}
You're not capitalizing the last class correctly. You've got:
class HTHSStudent extends Student
{
double gpa;
public HthsStudent (String firstName, String lastName, int gradeLevel, double gpa)
It should be
class HTHSStudent extends Student
{
double gpa;
public HTHSStudent (String firstName, String lastName, int gradeLevel, double gpa)
or even better:
class HthsStudent extends Student {
private double gpa;
public HthsStudent (String firstName, String lastName, int gradeLevel, double gpa)
Note that for Java identifiers, capitalization matters
Also as noted in my comments, you've got another unrelated problem in that your studentId field should most definitely not be static. This field needs to be unique for each Student object, and if you make it static, it will become a property of the class, and thus be the same for all Students. If you made it static to fix a compiler error, then you fixed the wrong error. The correct fix is to not try to reference it in a static way, off the class.
Related
I don't really know if my question makes sense but my assignment says:
"Write a third class, StudentRecord, that has two attributes:
Student stu;
Address addr;
and two constructors. The first constructor is given a Student object and an Address object to initialize the attributes. The second constructor is given a first name, a last name, a student ID, a gpa, a street address, a city, a state, and a zipcode and uses these to initialize the attributes"
I don't understand how exactly I'm supposed to make two constructors take info from two different java files.
Here's the code I have for the third class named "StudentRecord".
I have no doubt it's incorrect.
public class StudentRecord {
Student stu;
Address addr;
public StudentRecord() {
Student stu;
Address addr;
}
public StudentRecord(String _fName, String _lName, int _id, double _gpa, String _street, String _city, String _state, int _zip){
}
public String toString() {
return String.format(stu + "\n" + addr);
}
}
Here's the code I have for the TestStudentRecord class, all I get is
"null null" when I run the program.
public class TestStudentRecord {
public static void main(String[] args) {
StudentRecord stu1 = new StudentRecord("Jane", "Brown", 182765, 2.333, "13 Flower St.", "Pulteneyville", "NY", 14386);
System.out.println(stu1);
}
}
All I get is "null null" when I run the program instead of the toString method giving me the student info I have typed into the test class.
For those asking for the Student and Address classes, here you go:
public class Student {
// attributes of a Student
private String firstName;
private String lastName;
private int studentId;
private double gpa;
/**
* Student constructor.
* #param _fName student's first name
* #param _lName student's last name
* #param _id student's id number
* #param _gpa students GPA
*/
public Student(String _fName, String _lName, int _id, double _gpa) {
firstName = _fName;
lastName = _lName;
studentId = _id;
gpa = _gpa;
}
/**
* getFirstName - Accessor for first name
* #return the student's first name
*/
public String getFirstName() {
return firstName;
}
/**
* getLastName - Accessor for last name
* #return the student's last name
*/
public String getLastName() {
return lastName;
}
/**
* getId - Accessor for ID
* #return the student's ID
*/
public int getStudentId() {
return studentId;
}
/**
* getGpa - Accessor for gpa
* #return the student's gpa
*/
public double getGpa() {
return gpa;
}
/**
* setFirstName - Mutator for first name
* #param the new first name
*/
public void setFirstName(String _fName) {
firstName = _fName;
}
/**
* setLastName - Mutator for last name
* #param the new last name
*/
public void setLastName(String _lastName) {
lastName = _lastName;
}
/**
* setStudentId - Mutator for ID
* #param the new ID
*/
public void setStudentId(int _id) {
studentId = _id;
}
/**
* setGpa - Mutator for gpa
* #param the new gpa
*/
public void setGpa(double _gpa) {
gpa = _gpa;
}
// toString Method
public String toString() {
return String.format(getLastName() + ", " + getFirstName() + "\n" + "ID: " + getStudentId() + " GPA: %3.1f", getGpa());
}
}
public class Address {
private String street;
private String city;
private String state;
private int zip;
public Address(String _street, String _city, String _state, int _zip) {
street = _street;
city = _city;
state = _state;
zip = _zip;
}
// Accessors
public String getStreet() {
return street;
}
public String getCity() {
return city;
}
public String getState() {
return state;
}
public int getZip() {
return zip;
}
// Mutators
public void setStreet(String _street) {
street = _street;
}
public void setCity(String _city) {
city = _city;
}
public void setState(String _state) {
state = _state;
}
public void setZip(int _zip) {
zip = _zip;
}
// toString Method
public String toString() {
return String.format(getStreet() + "\n" + getCity() + ", " + getState() + " " + getZip());
}
}
would suggest you to please follow below approach to initialize your object through argumented construtor.
public class StudentRecord {
Student stu;
Address addr;
public StudentRecord() {
Student stu;
Address addr;
}
public StudentRecord(String _fName, String _lName, int _id, double _gpa, String _street, String _city, String _state, int _zip){
this.stu = new Student(_fName, _lName, _id, _gpa);
this.addr=new Address(_street,_city,_state,_zip);
}
public String toString() {
return String.format(stu + "\n" + addr);
}
}
As you have already overided toString method in address and student class so you will get the object.
Your constructor is like below. Empty Constructor will not assign values to your class variables.
public StudentRecord(String _fName, String _lName, int _id, double _gpa, String _street, String _city, String _state, int _zip){
}
it should be like below as mentioned by Eran.
public StudentRecord(String _fName, String _lName, int _id, double _gpa, String _street, String _city, String _state, int _zip){
this.stu = new Student(_fName, _lName, _id, _gp);
this.addr = new Address(_street, _city, _state, _zip);
}
Now your toString will have the values for stu and addr. Which will get printed.
You have to initilize the variables with this.{variable name} = {variable name}.
Also it is often better to chain the Constructors (see How do I call one constructor from another in Java?), in this way changes in classes, with many constructors, are way easier to implement.
I would also suggsest to rename your variables, because in Java they should not start with an underscore (see https://www.javatpoint.com/java-naming-conventions).
public class StudentRecord {
Student student;
Address addr;
public StudentRecord(Student student, Address addr) {
this.student = student;
this.addr = addr;
}
public StudentRecord(String fName, String lName, int id, double gpa, String street, String city, String state, int zip){
this(new Student(fName, lName, id, gpa),
new Address(street,city,state,zip));
}
public String toString() {
return String.format(student + "\n" + addr);
}
}
I have been looking around online, and I am still unsure of how to call a method in my child class. I am trying to call the pay() method in Executive, and when I type in the following code into my if statement, I keep getting an error.
staff[3].awardBonus(bonus);
I keep getting an error with this method. I'm not sure how to call that method... Thanks for any help!`import java.util.Scanner;
import java.util.Scanner;
public class Tester
{
public static void main (String args[])
{
Scanner scan = new Scanner(System.in);
StaffMember[] staff = new StaffMember[4];
String internName = "Susan 2";
String empName = "Tyler O.";
String hrName = "Becky R.";
String execName = "Daniel H.";
String address = "Brighton";
String phone = "420 - 0000";
String SSN = "12345789";
double rate = 1000;
staff [0] = new Intern(internName, address, phone);
staff [1] = new Employee(empName, address, phone, SSN, rate);
staff [2] = new HourlyEmployee(hrName, address, phone, SSN, rate);
staff [3] = new Executive(execName, address, phone, SSN, rate);
for (StaffMember staffPrint : staff)
{
System.out.println (staffPrint.toString() + "\n");
}
System.out.println("If you would like to give an executive a bonus, press 1. \nIf you would like to increase the hours of an hourly employee, press 2.");
int input = scan.nextInt();
if(input == 1)
{
double bonus = 0;
System.out.println("Enter the bonus for your employee: ");
bonus = scan.nextDouble();
}
}
Here is the Executive class, Employee class and the StaffMember class
public class Executive extends Employee
{
public Executive(String name, String address, String phone, String SSN, double rate)
{
super(name, address, phone, SSN, rate);
}
public double pay()
{
double money = super.pay();
return money;
}
public String toString()
{
String employee = super.toString();
return employee;
}
public void awardBonus(double execBonus)
{
rate += execBonus;
}
}
Employee
public class Employee extends StaffMember
{
String SSN;
double rate;
public Employee(String name, String address, String phone, String SSN, double rate)
{
super(name, address, phone);
this.SSN = SSN;
this.rate = rate;
}
public double pay()
{
return rate;
}
public String toString()
{
String employee = "";
employee = ("Name: " + name + "\nAddress: " + address + "\nPhone Number: " + phone + "\nSocial Security Number: " + SSN + "\nPay: " + pay());
return employee;
}
}
StaffMember
public abstract class StaffMember
{
String name;
String address;
String phone;
public StaffMember(String name, String address, String phone)
{
this.name = name;
this.address = address;
this.phone = phone;
}
public String toString()
{
String employee = "";
employee = ("Name: " + name + "\nAddress: " + address + "\nPhone Number: " + phone);
return employee;
}
public abstract double pay();
}
staff is a StaffMember array. When you reference any item from it (as you do it staff[3]), you get a StaffMember.
StaffMember does not have a method awardBonus().
Your problem is that you are trying to call an undefined method on your StaffMember object. In fact the method awardBonus() was not defined in your StaffMember class.
And in the code staff[3].awardBonus(bonus) you were trying to call awardBonus() on staff[3] which is a StaffMember instance.
By providing an awardBonus for all StaffMembers, you can call it on a StaffMember. For instance:
public abstract class StaffMember
{
public void awardBonus(double bonus) {
if (bonus > 0) {
throw new IllegalStateException("Only executives receive a bonus");
}
}
...
public class Executive extends StaffMember
{
#Override
public void awardBonus(double bonus) {
P.S. be careful to inform the company on this.
You can use:
// Check if staff[3] is really an Executive
if(staff[3] instanceof Executive) {
// Cast staff[3] to an Executive
Executive executive = ((Executive)staff[3]);
// Now you can call awardBonus
executive.awardBonus(bonus);
}
Because staff is an StaffMember-array which doesn't contains the methode awardBonus.
You know that staff[3] is an Executive, but your program doesn't. Therefore you have to check if staff[3] is an instanceof Executive so you can safely cast it to an Executive with Executive executive = (Executive)staff[3].
I have a practice problem that I need to complete and have done everything however I cannot get the output to match whats needed. I have tried some of the google answers but nothing seems to be working. Below is the code and the output I get vs what I want. We are not allowed to modify the main method but only the classes.
I am just confused on how to make the output from each class start on a new line.
There is this statement in the instructions but I don't understand how to go about it:
the Student class should have a public display function that calls the parent class’ display
function,
Code:
public class H255{public static void main (String[] args){while (JPL.test()){
Person pObj = new Person("Albert","Einstein");
Student sObj = new Student("John","Smith",123456,"First Year","Pullan");
Teacher tObj = new Teacher("Wayne","Pullan","Computer Science",100000,"Lecturer");
System.out.println("Person :");
pObj.Display();
System.out.println("");
System.out.println("Student :");
sObj.Display();
System.out.println("");
System.out.println("Teacher :");
tObj.Display();
}}}
class Person{
private String FirstName;
private String LastName;
public Person(String fName, String lName){
this.FirstName = fName;
this.LastName = lName;
}
public void Display(){
System.out.println("First Name: " + FirstName + " Last Name: " + LastName);
}
}
class Student extends Person{
private int id;
private String standard;
private String instructor;
public Student(String fName, String lName, int nId, String stnd, String instr){
super(fName, lName);
this.id = nId;
this.standard = stnd;
this.instructor = instr;
}
public void Display(){
System.out.println("ID: " + id + "Standard: " + standard + "Instructor: " + instructor);
}
}
class Teacher extends Person{
private String mainSubject;
private int salary;
private String type;
public Teacher(String fName, String lName, String sub, int slry, String sType){
super(fName, lName);
this.mainSubject = sub;
this.salary = slry;
this.type = sType;
}
public void Display(){
System.out.println("Main Subject: " + mainSubject + "Salary: "
+ salary + "Type: " + type );
}
}
Output:
the writing of main method like these code:
System.out.print("Person :");
pObj.Display();
System.out.print("Student :");
sObj.Display();
System.out.print("Teacher :");
tObj.Display();
because:the println method has a build in wrap feature, so just replace println with print.
I am new to using Java - so please forgive my ignorance. Would you be able to look at this code and let me know why I get error:
cannot find symbol - variable
when I call the constructor method. I am using BlueJ. Basically I put in the variables and then hit ok to create an object but it comes up with that error.
/**
* Write a description of class Membership here.
*
* #author (Gohar Warraich)
* #version (1.0)
*/
public class Membership
{
// instance variables - replace the example below with your own
private String firstname;
private String lastname;
private String phonenumber;
private int idnumber;
/**
* Constructor for objects of class Membership
*/
public Membership(String newfirstname, String newlastname, String newphonenumber, int newidnumber)
{
// initialise instance variables
firstname = newfirstname;
lastname = newlastname;
phonenumber = newphonenumber;
idnumber = newidnumber;
}
/**
* Accessor method of Membership
*/
public String getfirstname()
{
return firstname;
}
public String getlastname()
{
return lastname;
}
public String getphonenumber()
{
return phonenumber;
}
public int getidnumber()
{
return idnumber;
}
/**
* Mutator method of Membership
*/
public void setfirstname(String insertfirstname)
{
firstname = insertfirstname;
}
public void setlastname(String insertlastname)
{
lastname = insertlastname;
}
public void setphonenumber(String insertphonenumber)
{
phonenumber = insertphonenumber;
}
public void setid(int insertidnumber)
{
idnumber = insertidnumber;
}
public void printMembership()
{
System.out.println("The firstname is " + firstname + " The lastname is " + lastname +" The phoneNumber is "+ phonenumber +" The idNumber is " +idnumber);
}
}
#gohar, There isn't a problem in this code. It must be in your call to the constructor. I'll give you an example of what this should look like.
Membership membershipName = new Membership ("String", "String", "String", 0101)
0101 can be any int, and you can name the variable what ever you want by changing membershipName. Hope this helps. :)
i'm writing code for employee, manager, hourly worker for a class assignment but i've hit a problem that i can't figure out, the following is my code for employee followed by hourly worker. the problem is hourly worker won't compile, it's giving a "cannot find symbol constructor employee" error when i try to compile (employee class compiiles without issue. any suggestions please? i think i've been staring at it for so long i can no longer see the problem! thanks. pieter.
EMPLOYEE CLASS -
public class Employee
{
public String firstName;
public String lastName;
public double hourlyRate;
final static double NORMAL_WORKWEEK = 37.5;
public Employee(String firstName, String lastName, double hourlyRate)
{
setFirstName(firstName);
setLastName(lastName);
setHourlyRate(hourlyRate);
}
//Accessor and Mutator Methods for the employee's first name.
public String getFirstName()
{
return firstName;
}
public void setFirstName(String firstName)
{
firstName = firstName;
}
//Accessor and Mutator Methods for the employee's last name.
public String getLastName()
{
return lastName;
}
public void setLastName(String lastName)
{
lastName = lastName;
}
//Access and Mutator Methods for the employee's hourly rate.
public double getHourlyRate()
{
return hourlyRate;
}
public void setHourlyRate(double hourlyRate)
{
//If the user input is valid, update the employee's hour rate with the newly input value.
if(hourlyRate > 0)
{
hourlyRate = hourlyRate;
}
//Otherwise prevent an hour rate greater than zero being overwritten
else if(hourlyRate <=0)
{
if(hourlyRate <= 0)
{
hourlyRate = 0;
}
decorateConsole();
//Alert the user to their mistake.
System.out.println("Error ! ! ! - An attempt to set the employee " + this.firstName + " " + this.lastName + "'s hourly rate to zero was detected.\n");
decorateConsole();
}
}
public void printState()
{
decorateConsole();
System.out.println("[FIRST NAME] = " + firstName + " [LAST NAME] = " + lastName + " [HOURLY RATE] = " + hourlyRate + "\n");
decorateConsole();
}
public void decorateConsole()
{
System.out.println("+-< EMPLOYEE INFO >-------------------------------------------------------------------------------------------------------------------------+\n");
}
HOURLY WORKER CLASS -
public class HourlyWorker extends Employee
{
private double wage;
private double hours;
public HourlyWorker(String firstName, String lastName, double hourlyWage, double hoursWorked)
{
super(firstName, lastName);
this.wage = wage;
this.hours = hours;
}
public void setWage (double hourlyWage)
{
this.wage = wage;
}
public void getWage()
{
return wage;
}
public void setHours (double hours)
{
this.hours = hours;
}
public double getHours()
{
return hours;
}
}
You don't have a Employee constructor with two parameters:
super(firstName, lastName);
Try using:
super(firstName, lastName, 0.0);
EDIT as per tony request, here's a more detailed explanation.
With super(firstName, lastName); you're invoking ( trying to invoke ) a constructor in the class Employee which has two string parameters.
Reviewing the Employee class definition, we see you don't have such constructor, but you have one with three parameters:
public Employee(String firstName, String lastName, double hourlyRate)
So, the solution is to invoke that constructor instead. Since you don't have a default value for hourlyRate we can use 0.0 which is a double.
Other alternative would be to create a two parameter constructor in the Employee class
public Employee(String firstName, String lastName )
In the HourlyWorker constructor you tried to call the Employee constructor like this:
super(firstName, lastName);
but the Employee class doesn't have a constructor with two parameters. You need to pass a third parameter (hourly rate) like this:
super(firstName, lastName, 42);
In HourlyWorker you call
super(firstName, lastName);
but the Employee constructor is
Employee(String, String, double)
The signatures don't match.
EDIT: Incidentally, why does the HourlyWorker have a private wage member? How is it different (conceptually) to Employee.hourlyRate?
In your HourlyWorker class you are calling the constructor of Employee {super(firstname, lastname)} with two arguments but in Employee class you do not have any constructors that take two arguments.
You don't have a super constructor that takes only two arguments.
HourlyWorker's constructor tries to call super(firstName, lastName), but there's no such constructor declared in the parent class.
In your HourlyWorker class, you have the following line of code:
super(firstName, lastName);
But, there is no matching constructor in your employee class. Basically, the compiler is looking in your employee class for something like...
public Employee(String firstName, String lastName)
{
...
}
Define a new constructor, or call the constructor you've defined with the parameters you're missing.
You are calling HourlyEmployee's base class constructor (which is Employee's ctor) with 2 arguments instead of the 3 it wants.
Change the line in HourlyEmployee ctor from:
super(firstName, lastName);
to
super(firstName, lastName, hourlyWage);
Also, if you are still wanting to have a constructor like
public Employee(String firstName, String lastName)
{
...
}
and you know the default value from your double hourlyRate, you can try to write a new constructor like the next one:
`public Employee(String firstName, String lastName)
{
Employee(firstName, lastName, 0.0);
}`
There's something fishy going on around the else if here. It's repeated with another if and some curly braces missing. Indent your code properly and make sure the open curlys matches the closing ones.
if(hourlyRate > 0)
{
hourlyRate = hourlyRate;
}
//Otherwise prevent an hour rate greater than zero being overwritten
else if(hourlyRate <=0)
{
if(hourlyRate <= 0)
{
hourlyRate = 0;
}
decorateConsole();
Also, these kind of lines won't work as intended (you have three of them):
firstName = firstName;
It must be:
this.firstName = firstName;
Like you have in your second class.