Formatting Issues with Java Code - java

I am having trouble formatting Strings as I keep getting MissingFormatArgumentException error:
Exception in thread "main" java.util.MissingFormatArgumentException: Format specifier '%s'
at java.util.Formatter.format(Unknown Source)
at java.util.Formatter.format(Unknown Source)
at java.lang.String.format(Unknown Source)
at Employee.toString(Employee.java:36)
at CommissionEmployee.toString(CommissionEmployee.java:112)
at CommissionEmployeeTest.main(CommissionEmployeeTest.java:20)
Here is my code
Employee Java SuperClass File
public class Employee {
private final String firstName;
private final String lastName;
private final String socialSecurityNumber;
//SuperClass Argument Constructor
public Employee(String firstName, String lastName, String socialSecurityNumber)
{
this.firstName = firstName;
this.lastName = lastName;
this.socialSecurityNumber = socialSecurityNumber;
}
//return first name
public String getFirstName()
{
return firstName;
}
//return last name
public String getLastName()
{
return lastName;
}
//get Social Security number
public String getSocialSecurityNumber(){
return socialSecurityNumber;
}
public String toString(){
return String.format("%s: %s %s%n%s: %s%n%s:", "commission employee",getFirstName(), getLastName(), "social security number", getSocialSecurityNumber());
}
}
Commission Employee SubClass
public class CommissionEmployee extends Employee {
//private final String firstName;
//private final String lastName;
//private final String socialSecurityNumber;
private double grossSales; //gross weekly sales
private double commissionRate; //commission percentage
//five argument constructor
public CommissionEmployee(String firstName, String lastName, String socialSecurityNumber, double grossSales, double commissionRate)
{
//implicit call to Object's default constructor occurs here
super(firstName,lastName,socialSecurityNumber);
//if grossSales is invalid throw exception
if(grossSales < 0.0 )
throw new IllegalArgumentException("Gross sales must be >=0.0");
//if commissionRate is invalid throw Exception
if(commissionRate<= 0.0 && commissionRate >= 1.0)
throw new IllegalArgumentException("Commission rate must be > 0.0 and < 1.0");
//this.firstName = firstName;
//this.lastName = lastName;
//this.socialSecurityNumber = socialSecurityNumber;
this.grossSales = grossSales;
this.commissionRate = commissionRate;
} //end constructor
//return first name
/*public String getFirstName()
{
return firstName;
}
//return last name
public String getLastName()
{
return lastName;
}
//get Social Security number
public String getSocialSecurityNumber(){
return socialSecurityNumber;
}
*/
//set gross Sales amount
public void setGrossSales(double grossSales)
{
if(grossSales <0.0)
throw new IllegalArgumentException("Gross sales must be >= 0.0");
this.grossSales = grossSales;
}
//return gross Sales amount
public double getGrossSales()
{
return grossSales;
}
//set commissionRate
public void setCommissionRate(double commissionRate)
{
if(commissionRate <=0.0 || commissionRate >=1.0)
throw new IllegalArgumentException("Commission rate must be >0.0 and <1.0");
this.commissionRate = commissionRate;
}
//return commissionRate
public double getCommissionRate()
{
return commissionRate;
}
//calculate Earnings
public double earnings()
{
return getCommissionRate() * getGrossSales();
}
//return String representation of CommissionEmployee object
//indicates that this method overrides a superclass method
public String toString()
{
return String.format("%s: %.2f%n%s: %.2f", "commission employee",super.toString(),"gross sales",getGrossSales(),"commission rate", getCommissionRate());
//return String.format("%s: %s %s%n%s: %s%n%s: %.2f%n%s: %.2f", "commission employee",getFirstName(), getLastName(), "social security number", getSocialSecurityNumber(),"gross sales",getGrossSales(),"commission rate", getCommissionRate());
}
}
Commission EmployeeTest Java
public class CommissionEmployeeTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
CommissionEmployee employee = new CommissionEmployee("Sam","randomlastname","123-34-5678",50.20,20.40);
//get commission employee data
System.out.println("Employee information obtained by get methods:");
System.out.printf("%n%s %s%n", "First name is",employee.getFirstName());
System.out.printf("%s %s%n", "Last name is", employee.getLastName());
System.out.printf("%s %s%n", "Social Security number is", employee.getSocialSecurityNumber());
System.out.printf("%s %.2f%n", "Gross Sales is", employee.getGrossSales());
System.out.printf("%s %.2f%n", "Commission Rate is", employee.getCommissionRate());
employee.setGrossSales(5000);
employee.setCommissionRate(0.1);
System.out.printf("%n%s:%n%n%s%n","Updated employee information obtained by toString",employee.toString());
}
}
Edit: Fixed my issues
Do you guys have any suggestions as to how I can fix my code?

In %s: %s %s%n%s: %s%n%s in Employee.toString(), I count six occurrences of %s, but only five arguments. I think you want to remove the very last %s.

Related

How to get rid of syntax error on token "public" in main class?

I am getting a syntax error in my main class when I call the constructor from another class that I need for the main program to run. This program is focused on inheritance and the appropriate calling of constructors and arguments. This is the error message I get during compilation:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Syntax error on token "public", record expected after this token
at a6main.main(a6main.java:7)
This is the line of code that is causing the error:
PreferredCustomer c = new PreferredCustomer("Al", "222BurdSt", "2102223321", "46821",
"2000", true, "1000");
The rest of the code can be found below:
class person {
String Name;
String Address;
String Telephone;
person (String Name, String Address, String Telephone) {
this.Name = Name;
this.Address = Address;
this.Telephone = Telephone;
}
String getName() {
return Name;
}
String getAddress() {
return Address;
}
String getTelephone() {
return Telephone;
}
void setName(String Name) {
this.Name = Name;
}
void setAddress(String Address) {
this.Address = Address;
}
void setTelephone(String Telephone) {
this.Telephone = Telephone;
}
}
public class customer extends person {
String number;
boolean OnMailingList;
//constructor and getters and setters
customer (String Name, String Address, String Telephone, String number, boolean OnMailingList) {
//inherit persons information
super(Name, Address, Telephone);
this.number = number;
this.OnMailingList = OnMailingList;
}
String getnumber() {
return number;
}
void setnumber(String number) {
this.number = number;
}
boolean OnMailingList () {
return OnMailingList;
}
void setOnMailingList(boolean OnMailingList) {
this.OnMailingList = OnMailingList;
}
}
public class PreferredCustomer extends customer {
private int purchase;
double discount;
/**public constructor so its accessible to main
* else ifs for certain percentage of discounts
* getters and setters for purchase and discount
* super to inherit other features from other classes */
public int getpurchase() {
return purchase;
}
public double getdiscount () {
return this.discount;
}
public void setPurchase(int purchase) {
this.purchase = purchase;
}
public PreferredCustomer(String Name, String Address, String Telephone, String number, int pur,
boolean OnMailingList, double Discount, PreferredCustomer preferredCustomer) {
super(Name, Address, Telephone, number, OnMailingList);
this.purchase = pur;
preferredCustomer.discount = discount;
if (this.purchase>= 2000) {
this.discount = 10;
} else if (this.purchase>= 1500) {
this.discount = 7;
} else if (this.purchase>= 1000) {
this.discount = 6;
} else if (this.purchase >= 500) {
this.discount = 5;
}
}
}
public class a6main {
public static void main (String [] args) {
public PreferredCustomer() {
}
PreferredCustomer c = new PreferredCustomer("Al", "222BurdSt", "2102223321", "46821","2000", true, "1000");
System.out.println("Name: " + c.getName());
System.out.println("Address: " + c.getAddress());
System.out.println("Telephone number: " + c.getTelephone());
System.out.println("Customer ID: " + c.getnumber());
System.out.println("Amount spent: " + c.getpurchase());
System.out.println("On mailing list: " + c.OnMailingList());
System.out.println("Discount: " + c.getdiscount());
}
}
You have several mistakes here. I've corrected them, and the program launches, providing the result:
Name: Al
Address: 222BurdSt
Telephone number: 2102223321
Customer ID: 46821
Amount spent: 2000
On mailing list: true
Discount: 10.0
Remove PreferredCustomer constructor from the main method. It can't be a part of a
method, it is a part of a class. Then, the constructor for PreferredCustomer is already present in PreferredCustomer class.
Hopefully, your customer and PreferredCustomer classes are in separate files? If not, put them in separate files named customer.java and PreferredCustomer.java. In PreferredCustomer class constructor, remove PreferredCustomer preferredCustomer from arguments. It's redundant: why you need to pass one customer into another? Do customers have any relationships with each other? Now the number of arguments will match when you call the constructor (and don't use strings "2000", "1000" where should be integers):
PreferredCustomer c = new PreferredCustomer("Al", "222BurdSt", "2102223321", "46821",
2000, true, 1000);
Further in the PreferredCustomer constructor, use this instead of preferredCustomer here: this.discount = Discount; and print Discount with upper case, as in the signature of the constructor.
As a result, the code of the constructor should be:
public PreferredCustomer(String Name, String Address, String Telephone, String number, int pur, boolean OnMailingList, double Discount) {
super(Name, Address, Telephone, number, OnMailingList);
this.purchase = pur;
this.discount = Discount;
if (this.purchase>= 2000) {
this.discount = 10;
} else if (this.purchase>= 1500) {
this.discount = 7;
} else if (this.purchase>= 1000) {
this.discount = 6;
} else if (this.purchase >= 500) {
this.discount = 5;
}
}
The main method in a6main class:
public static void main (String [] args) {
PreferredCustomer c = new PreferredCustomer("Al", "222BurdSt", "2102223321", "46821", 2000, true, 1000);
System.out.println("Name: " + c.getName());
System.out.println("Address: " + c.getAddress());
System.out.println("Telephone number: " + c.getTelephone());
System.out.println("Customer ID: " + c.getnumber());
System.out.println("Amount spent: " + c.getpurchase());
System.out.println("On mailing list: " + c.OnMailingList());
System.out.println("Discount: " + c.getdiscount());
}
And take care of naming conventions, as other people pointed.

Inheritance - Creating a class Commission Employee from class Employee and testing

Good Morning, I've been given the assignment to:
rewrite the CommissionEmployee class as a subclass of Employee. CommissionEmployee should contain only the instance variables and methods that are not declared in superclass Employee. CommissionEmployee's constructor should invoke Employee's constructor and CommissionEmployee's toString method should invoke Employee's toString method.
Create a Driver class to test your new CommissionEmployee class. Prompt the user to input the first name, last name, social security number, gross sales, and commission rate and create a CommissionEmployee object, using the toString method to print its information.
The issue I seem to be having is class CommissionEmployeeTest will not output what I've placed in my toString method of class CommissionEmployee. I feel like like my superclass Employee is correct as well as me test class but my belief is the error lies somewhere in the method I've created to determine the earnings. The output I'm looking for is
Employees First Name Last Name
Social Security NUmber
Earnings
Earnings would be the total of gross sales + (commission rate * gross sales)
Here is what I have along with the error:
class Employee
public class Employee extends Object {
protected final String firstName;
protected final String lastName;
protected final String socialSecurityNumber;
public Employee(String firstName, String lastName, String socialSecurityNumber) {
this.firstName = firstName;
this.lastName = lastName;
this.socialSecurityNumber = socialSecurityNumber;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getSocialSecurityNumber() {
return socialSecurityNumber;
}
#Override
public String toString() {
return String.format(firstName, lastName, socialSecurityNumber);
}
}
class CommissionEmployee
public class CommissionEmployee extends Employee {
private double grossSales;
private double commissionRate;
private double earnings;
public CommissionEmployee(String firstName, String lastName, String socialSecurityNumber, double grossSales,
double commissionRate, double earnings) {
super(firstName, lastName, socialSecurityNumber);
if (grossSales < 0.0)
throw new IllegalArgumentException("Gross sales must be >= 0.0");
if (commissionRate <= 0.0 || commissionRate >= 1.0)
throw new IllegalArgumentException("Commission rate must be > 0.0 and < 1.0");
this.grossSales = grossSales;
this.commissionRate = commissionRate;
}
public void setGrossSales(double grossSales) {
if (grossSales < 0.0)
throw new IllegalArgumentException("Gross sales must be >= 0.0");
this.grossSales = grossSales;
}
public double getGrossSales() {
return grossSales;
}
public void setCommissionRate(double commissionRate) {
if (commissionRate <= 0.0 || commissionRate >= 1.0)
throw new IllegalArgumentException("Commission rate must be > 0.0 and < 1.0");
this.commissionRate = commissionRate;
}
public double getCommissionRate() {
return commissionRate;
}
public Double earnings(double d) {
return earnings(grossSales+ (commissionRate * grossSales));
}
public double getEarnings() {
return earnings;
}
public void setEarnings(double earnings) {
this.earnings = earnings;
}
#Override
public String toString() {
return String.format("%s: %s %s%n%s: %s%n%s: %.2f%n%s: %.2f%n%s: %.2f%n%s",
"commission employee", firstName, lastName,
"social security number", socialSecurityNumber,
"Total earnings", earnings(earnings));
}
public void setFirstName(String firstName) {
}
public void setLastName(String lastName) {
}
public void setSocialSecurityNumber(String socialSecurityNumber) {
}
public void setGrossSales(String grossSales) {
}
public void setCommissionRate(String commissionRate) {
}
}
class CommissionEmployeeTest
//CommissionEmployee test program.
import java.util.Scanner;
public class CommissionEmployeeTest {
public static void main(String[] args) { // instantiate CommissionEmployee object
CommissionEmployee employee =
new CommissionEmployee(null, null, null, 0, .1, 0);
Scanner input = new Scanner(System.in);
// get commission employee data
System.out.printf(
"Employee information obtained by get methods:%n");
System.out.printf("Enter employee's First name:");
String firstName = input.nextLine();
employee.setFirstName(firstName);
System.out.printf("Enter employee's last name:");
String lastName = input.nextLine();
employee.setLastName(lastName);
System.out.printf("Enter employee's social security number:");
String socialSecurityNumber = input.nextLine();
employee.setSocialSecurityNumber(socialSecurityNumber);
System.out.printf("Gross sales for employee:");
String grossSales = input.nextLine();
employee.setGrossSales(grossSales);
System.out.printf("Commission rate for employee:");
String commissionRate = input.nextLine();
employee.setCommissionRate(commissionRate);
System.out.printf("%n%s:%n%n%s%n",
"Updated employee information obtained by toString",
employee.toString());
}
}
Error
Employee information obtained by get methods:
Enter employee's First name:John
Enter employee's last name:Doe
Enter employee's social security number:123456789
Gross sales for employee:4000.00
Commission rate for employee:.1
Exception in thread "main" java.lang.StackOverflowError
at CommissionEmployee.earnings(CommissionEmployee.java:45)
I've tried manipulating my toString method in CommissionEmployee as well as my method to determine earnings but I feel like I'm spinning my wheels. I appreciate any help. I have 1 week left in class and feel like I can contribute more information each week when I post a question then I did the last. Thank you in advance.
I have resolved the issue. After reviewing and revising(several times) I have found my answer. I needed revision on my toString method as well as my earnings method. Cleaned up quite a bit of the code and resolved.

ERROR actual and formal argument lists differ in length

constructor Student in class javaapplication 14.Student cannot be
applied to given types; required:
java.lang.String,int,java.lang.String,java.lang.String,double found:
java.lang.String,double reason: actual and formal argument lists
differ in length
This is the line that gives me error
super(idNum, gpa);
here is my code:
package javaapplication14;
public class JavaApplication14
{
public static void main(String[] args)
{
Person bob = new Person("Coach Bob", 27, "M");
System.out.println(bob);
Student lynne = new Student("Lynne Brooke", 16, "F", "HS95129", 3.5);
System.out.println(lynne);
Teacher mrJava = new Teacher("Duke Java",34,"M","Computer Science",50000);
System.out.println(mrJava);
}
}
class Person
{
protected String myName ;
protected int myAge;
protected String myGender;
public Person(String name, int age, String gender)
{
myName = name;
myAge = age ;
myGender = gender;
}
#Override
public String toString()
{
return myName + ", age: " + myAge + ", gender: " +myGender;
}
//These are the set methods
void setName(String name)
{
myName = name;
}
void setAge(int age)
{
myAge = age ;
}
void setGender(String gender)
{
myGender = gender;
}
//These are the get methods
String myName()
{
return myName;
}
int myAge()
{
return myAge;
}
String myGender()
{
return myGender;
}
}
class Student extends Person
{
protected String myIdNum;
protected double myGPA;
public Student(String name, int age, String gender,String idNum, double gpa)
{
super(name, age, gender);
myIdNum = idNum;
myGPA = gpa;
}
//These are the set methods
void setmyIdNum(String idNum)
{
myIdNum = idNum;
}
void setmyGPA(double gpa)
{
myGPA = gpa;
}
#Override
public String toString()
{
return super.toString() + ", student id: " + myIdNum + ", gpa: " + myGPA;
}
public String myIdNum()
{
return myIdNum;
}
double myGPA()
{
return myGPA;
}
}
class Teacher extends Person
{
public double mySalary;
public String mysubjectName;
public Teacher( String name, int age, String gender, String
subjectName,double salary )
{
super(name, age, gender);
mysubjectName = subjectName;
mySalary = salary;
}
//These are the setter methods
void setsubjectname(String subjectName)
{
mysubjectName = subjectName;
}
void setsalary(double Salary)
{
mySalary = Salary;
}
#Override
public String toString()
{
return super.toString() + ", subject name: " + mysubjectName + ", Salary: "
+ mySalary;
}
//These are the getter methods
public String getsubjectname(String subjectName)
{
return subjectName;
}
double getsalary(double Salary)
{
return Salary ;
}
class CollegeStudent extends Student
{
public String myMajor;
public int myYear;
public CollegeStudent(String name, int age,String gender,
String idNum, double gpa, int year, String major )
{
super(idNum, gpa);
myMajor = major;
myYear = year;
}
void setmajor(String Major)
{
myMajor = Major;
}
void setyear(int Year)
{
myYear = Year;
}
#Override
public String toString()
{
return super.toString() + ", major: " + myMajor + ", Year: " + myYear;
}
//These are the getter methods
public String getmajor(String myMajor)
{
return myMajor;
}
public int getyear(int myYear)
{
return myYear ;
}
}
}
There is no such constructor with two parameters in Student class
The class Student and also the class Person has no constuctor with the signature (String, double).
So you have to create this constructor in one of the superclasses or you have to call an other constructor.
Your super class Student has following constructor with 5 parameter
public Student(String name, int age, String gender,String idNum, double gpa)
But, at CollegeStudent constructor, super(idNum, gpa); expect a constructor with two parameter Student(String idNum, double gpa), which is missing in superclass. So, define a constructor at Student class like:
class Student extends Person {
public Student(String idNum, double gpa){
}
}

Command-line argument

I'm learning command-line in JAVA now. I'm a beginner. I did a hard code for my project but I don't know how to apply command-line.
public class SalesRep
private String firstName;
private String lastName;
private String employeeID;
private double grossSales;
private double commissionRate;
public SalesRep(String[] args)
{
if (args.length != 5)
System.out.printf("Error");
else
{
firstName = args[0];
lastName = args[1];
employeeID = args[2];
grossSales = Double.parseDouble(args[3]);
commissionRate = Double.parseDouble(args[4]);
}
if (grossSales < 0.0)
throw new IllegalArgumentException
("Gross sale must be greater than or equal 0.0");
if (commissionRate <= 0.0 || commissionRate >= 1.0)
throw new IllegalArgumentException
("Comission rate must be in between 0.0 and 1.0");
}
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
public String getEmployeeID()
{
return employeeID;
}
public void setGrossSales(double grossSales)
{
if (grossSales < 0.0)
throw new IllegalArgumentException
("Gross sales must be greater than or equal 0.0");
this.grossSales = grossSales;
}
public double getGrossSales()
{
return grossSales;
}
public void setCommissionRate(double commissionRate)
{
if (commissionRate <= 0.0 || commissionRate >= 1.0)
throw new IllegalArgumentException
("Comission rate must be in between 0.0 and 1.0");
this.commissionRate = commissionRate;
}
public double getCommissionRate()
{
return commissionRate;
}
public double earnings()
{
return getCommissionRate() * getGrossSales();
}
#Override
public String toString()
{
return String.format("%s: %s %s%n%s: %s%n%s: %.2f%n%s: %.2f",
"Sale Representatives", firstName, lastName,
"Employee ID", employeeID,
"Gross Sales", grossSales,
"Commission Rate", commissionRate);
}
I know something wrong with command line argument. But I don't know how to fix it. Can anyone help me please?
Your program is going into this condition :
if (args.length != 5)
System.out.printf("Error");
Hence, the "Error" printed in the output.
To run your program with command line arguments, use:
java SalesRepTest arg0 arg1 arg2 arg3 arg4
where arg0,...,arg4 represent your arguments.
Well the right Code is:
public class SalesRep{
private String firstName;
private String lastName;
private String employeeID;
private double grossSales;
private double commissionRate;
public SalesRep(String[] args)
{
if (args.length != 5)
System.out.printf("Error");
else
{
firstName = args[0];
lastName = args[1];
employeeID = args[2];
grossSales = Double.parseDouble(args[3]);
commissionRate = Double.parseDouble(args[4]);
}
if (grossSales < 0.0)
throw new IllegalArgumentException
("Gross sale must be greater than or equal 0.0");
if (commissionRate <= 0.0 || commissionRate >= 1.0)
throw new IllegalArgumentException
("Comission rate must be in between 0.0 and 1.0");
}
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
public String getEmployeeID()
{
return employeeID;
}
public void setGrossSales(double grossSales)
{
if (grossSales < 0.0)
throw new IllegalArgumentException
("Gross sales must be greater than or equal 0.0");
this.grossSales = grossSales;
}
public double getGrossSales()
{
return grossSales;
}
public void setCommissionRate(double commissionRate)
{
if (commissionRate <= 0.0 || commissionRate >= 1.0)
throw new IllegalArgumentException
("Comission rate must be in between 0.0 and 1.0");
this.commissionRate = commissionRate;
}
public double getCommissionRate()
{
return commissionRate;
}
public double earnings()
{
return getCommissionRate() * getGrossSales();
}
#Override
public String toString()
{
return String.format("%s: %s %s%n%s: %s%n%s: %.2f%n%s: %.2f",
"Sale Representatives", firstName, lastName,
"Employee ID", employeeID,
"Gross Sales", grossSales,
"Commission Rate", commissionRate);
}
public static void main(String [] args){
SalesRep s = new SalesRep(args);
}
}
then you need to complie your code like
javac SalesRep.java
then your can run and supply commandline arguments like this:
java SalesRep arg1 arg2 arg3 arg4 arg4
Ok this will Work. you cannot supply commandline argument to constructor, it can be only for main method, but you can pass commandline argument as parameter to constructor.

Constructors from extended class in Java

I'm having some trouble with a hw assignment. In one assignment, we had to create a Person class. Mine was:
public class Person
{
String firstName;
String lastName;
String telephone;
String email;
public Person()
{
firstName = "";
lastName = "";
telephone = "";
email = "";
}
public Person(String firstName)
{
this.firstName = firstName;
}
public Person(String firstName, String lastName, String telephone, String email)
{
this.firstName = firstName;
this.lastName = lastName;
this.telephone = telephone;
this.email = email;
}
public String getFirstName()
{
return firstName;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public String getLastName()
{
return lastName;
}
public void setLastName(String lastName)
{
this.lastName = lastName;
}
public String getTelephone()
{
return telephone;
}
public void setTelephone(String telephone)
{
this.telephone = telephone;
}
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
public boolean equals(Object otherObject)
{
// a quick test to see if the objects are identical
if (this == otherObject) {
return true;
}
// must return false if the explicit parameter is null
if (otherObject == null) {
return false;
}
if (!(otherObject instanceof Person)) {
return false;
}
Person other = (Person) otherObject;
return firstName.equals(other.firstName) && lastName.equals(other.lastName) &&
telephone.equals(other.telephone) && email.equals(other.email);
}
public int hashCode()
{
return 7 * firstName.hashCode() +
11 * lastName.hashCode() +
13 * telephone.hashCode() +
15 * email.hashCode();
}
public String toString()
{
return getClass().getName() + "[firstName = " + firstName + '\n'
+ "lastName = " + lastName + '\n'
+ "telephone = " + telephone + '\n'
+ "email = " + email + "]";
}
}
Now we have to create a Loan class that uses Person as an attribute, and then extend that Loan class. My Loan class is:
public abstract class Loan
{
public void setLoanId(int nextId)
{
loanId = nextId;
nextId++;
}
public int getLoanId()
{
return loanId;
}
public void setInterestRate(double interestRate)
{
this.interestRate = interestRate;
}
public double getInterestRate()
{
return interestRate;
}
public void setLoanLength(int loanLength)
{
this.loanLength = loanLength;
}
public int getLoanLength()
{
return loanLength;
}
public void setLoanAmount(double loanAmount)
{
this.loanAmount = loanAmount;
}
public double getLoanAmount(double loanAmount)
{
return loanAmount;
}
public void printPayments()
{
double monthlyInterest;
double monthlyPrincipalPaid;
double newPrincipal;
int paymentNumber = 1;
double monthlyInterestRate = interestRate / 1200;
double monthlyPayment = loanAmount * (monthlyInterestRate) /
(1 - Math.pow((1 + monthlyInterestRate),( -1 * loanLength)));
// amortization table
while (loanAmount != 0) {
monthlyInterest = loanAmount * monthlyInterestRate;
monthlyPrincipalPaid = monthlyPayment - monthlyInterest;
newPrincipal = loanAmount - monthlyPrincipalPaid;
loanAmount = newPrincipal;
System.out.println("Payment Number | Interest | Principal | Loan Balance");
System.out.printf("%d, %.2f, %f, %f", paymentNumber++, monthlyInterest, newPrincipal, loanAmount);
}
}
/*
//method to print first payment
public double getFirstPayment()
{
}
method to print last payment
public double getLastPayment()
{
}*/
private Person client;
private int loanId;
private double interestRate;
private int loanLength;
private double loanAmount;
private static int nextId = 1;
}
And then extended the Loan class with CarLoan class, there is a function prototype of:
public CarLoan(Person client, double vehiclePrice, double downPayment, double salesTax,
double interestRate, CAR_LOAN_TERMS length)
I'm confused on how I use the Person constructor from the superclass. I cannot necessarily do
super(client);
in my constructor which is what the book did with some primitive types in their example. Not sure what the correct thing to do is... Any thoughts? Thanks!
CarLoan should not extend Person. That makes no sense since a CarLoan can't be a Person.
But Person can be a class variable in the CarLoan class.
public class CarLoan {
private Person client;
private double vehiclePrice;
public CarLoan(Person client, double vehiclePrice, double downPayment, double salesTax, double interestRate, CAR_LOAN_TERMS length) {
this.client = client;
this.vehiclePrice = vehiclePrice;
..
}
}
It looks like you want to be using composition in stead of inheritance.
In plain english, a CarLoan has a client (of type Person). A CarLoan itself is not a Person (which inheritance would suggest).
So you should do what Espen suggests (composition), in stead of CarLoan extends Person (inheritance).
A possibly legit use of inheritance would be:
class Waiter extends Person {
String employeeId;
// A waiter is a person with some extra information
public Waiter(String firstName, String lastName, String telephone,
String email, String employeeId) {
super(firstName, lastName, telephone, email); // must be first
this.employeeId = employeeId;
}
}
If CarLoan is to extend Person, then Person becomes the superclass of CarLoan.
From within the constructor of CarLoan you must always call one of the Person constructors via the super keyword before any other processing takes place.
However, it seems to me very much like you must be confused, as your prototype method passes an instance of Person to CarLoan. Further, I cannot see why a class called CarLoan would extend a person.

Categories