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.
Related
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.
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.
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.
I keep getting a nullPointerException and the rest of my code won't run. I have two classes setup. One is the SalesPerson and the other contains the main method. Line 42 is marked and that is where the nullPointerException occurs.
This is line 42
System.out.printf("%-20s %15.2f %14.2f %n", list[i].getFirstName() + " " + list[i].getLastName(), list[i].getTotalSales(), list[i].getSalary());
public class SalesPerson {
private String firstName;
private String lastName;
private double firstSales;
private double secondSales;
private double thirdSales;
private double fourthSales;
private double totalSales;
private double salary;
public SalesPerson(String lastName, String firstName, double firstSales,
double secondSales, double thirdSales, double fourthSales,
double totalSales, double salary) {
this.lastName = lastName;
this.firstName = firstName;
this.firstSales = firstSales;
this.secondSales = secondSales;
this.thirdSales = thirdSales;
this.fourthSales = fourthSales;
this.totalSales = totalSales;
this.salary = salary;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public double getTotalSales() {
return totalSales;
}
public void setTotalSales(double totalSales) {
this.totalSales = totalSales;
}
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 double getFirstSales() {
return firstSales;
}
public void setFirstSales(double firstSales) {
if (firstSales >= 0) {
this.firstSales = firstSales;
} else {
System.out.println("First sales must be greater than zero.");
}
}
public double getSecondSales() {
return secondSales;
}
public void setSecondSales(double secondSales) {
if (secondSales >= 0) {
this.secondSales = secondSales;
} else {
System.out.println("Second sales must be greater than zero.");
}
}
public double getThirdSales() {
return thirdSales;
}
public void setThirdSales(double thirdSales) {
if (thirdSales >= 0) {
this.thirdSales = thirdSales;
} else {
System.out.println("Third sales must be greater than zero.");
}
}
public double getFourthSales() {
return fourthSales;
}
public void setFourthSales(double fourthSales) {
if (fourthSales >= 0) {
this.fourthSales = fourthSales;
} else {
System.out.println("Fourth sales must be greater than zero.");
}
}
}
SECOND CLASS
import java.io.File;
import java.util.Scanner;
public class Assignment10 {
public static final int NUM_SALESPEOPLE = 20;
public static final double NUM_PER_SALARY = 25;
public static void main(String[] args) {
SalesPerson[] list = new SalesPerson[NUM_SALESPEOPLE];
try {
int people = 0;
Scanner fileInput = new Scanner(new File("A10.txt"));
while (fileInput.hasNext()) {
String lastName = fileInput.next();
String firstName = fileInput.next();
double firstSales = fileInput.nextDouble();
double secondSales = fileInput.nextDouble();
double thirdSales = fileInput.nextDouble();
double fourthSales = fileInput.nextDouble();
double totalSales = firstSales + secondSales + thirdSales + fourthSales;
double salary = NUM_PER_SALARY * totalSales;
SalesPerson person = new SalesPerson(lastName, firstName,
firstSales, secondSales, thirdSales, fourthSales, totalSales, salary);
list[people] = person;
people++;
}
} catch (Exception ex) {
System.out.println("Error opening file.");
}
System.out.println("Full Name Total Sales Salary");
System.out.println("========= =========== ======");
for (int i = 0; i < NUM_SALESPEOPLE; i++) {
System.out.printf("%-20s %15.2f %14.2f %n", list[i].getFirstName() + " " + list[i].getLastName(), list[i].getTotalSales(), list[i].getSalary());
}
System.out.println("===================================================");
}
}
You are creating an array of size 20. This array will hold only references to NULL. If in your file you have less than 20 entries you will end up with a nullpointerexception.
To be sure, try to print the value of people. If it less than 20 then this is normal.
Your file 'A10.txt' doesn't have 20 (correct) lines.
You should not create an Array. Use ArrayList and Iterator instead and you won't have such problems.
Simply add a check for null:
for (int i = 0; i < NUM_SALESPEOPLE; i++) {
if (list[i] != null) {
System.out.printf("%-20s %15.2f %14.2f %n", list[i].getFirstName() + " " + list[i].getLastName(), list[i].getTotalSales(), list[i].getSalary());
}
}
or declare
int people = 0;
two lines earlier (before your try-block) and use this number of actual read people as the upper bound in your for loop instead of NUM_SALESPEOPLE.
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.