My programming assignment tasked me with writing an increase/decreasePay abstract method that must be put in my abstract employee class. I can't seem to get the the method correct in HourlyWorker so that it will take increase or decrease the pay by a "percentage". My math is sound (monthly pay - or + (monthly pay * the percentage), but my output in my test class is coming out the same after increasing/decreasing pay. Any help?
Employee class:
abstract public class Employee
{
private String lastName;
private String firstName;
private String ID;
public abstract void increasePay(double percentage);
public abstract void decreasePay(double percentage);
public abstract double getMonthlyPay();
public Employee(String last, String first, String ID)
{
lastName = last;
firstName = first;
this.ID = ID;
}
public void setLast(String last)
{
lastName = last;
}
public void setFirst(String first)
{
firstName = first;
}
public void setIdNumber(String ID)
{
this.ID = ID;
}
public String getLastName()
{
return lastName;
}
public String getFirstName()
{
return firstName;
}
public String getName()
{
return firstName + lastName;
}
public String getIdNumber()
{
return ID;
}
}
HourlyWorkerClass
public class HourlyWorker extends Employee
{
private int hours;
private double hourlyRate;
private double monthlyPay;
public HourlyWorker(String last, String first, String ID, double rate)
{
super(last, first, ID);
hourlyRate = rate;
}
public void setHours(int hours)
{
this.hours = hours;
}
public int getHours()
{
return hours;
}
public void setHourlyRate(double rate)
{
if ( hours > 160 )
this.hourlyRate = hourlyRate * 1.5;
else
this.hourlyRate = rate;
}
public double getHourlyRate()
{
return hourlyRate;
}
public void setMonthlyPay(double monthlyPay)
{
monthlyPay = hourlyRate * hours;
}
public double getMonthlyPay()
{
return hourlyRate * hours;
}
public void increasePay(double percentage)
{
monthlyPay = monthlyPay* percentage;
}
public void decreasePay(double percentage)
{
monthlyPay = monthlyPay* percentage;
}
public String toString()
{
String result = "Name: " + getFirstName() + " " + getLastName() + "\nID: "
+ getIdNumber() + " \nHourly Rate: " + hourlyRate;
return result;
}
}
Testing class (currently testing increase
public class TestEmployee2
{
public static void main(String[] args)
{
Employee [] staff = new Employee[3];
Supervisor sup = new Supervisor("Boss", "Jim", "JB7865", 54000);
HourlyWorker hw1 = new HourlyWorker("Bee", "Busy", "BB1265", 11.95);
hw1.setHours(200);
staff[0] = sup;
staff[1] = hw1;
System.out.println(staff[0].getMonthlyPay());
staff[0].increasePay(5);
System.out.println(staff[0].getMonthlyPay());
System.out.println(staff[1].getMonthlyPay());
staff[1].increasePay(10);
System.out.println(staff[1].getMonthlyPay());
}
}
Supervisor class:
public class Supervisor extends Employee
{
private double annualSalary;
private double monthlyPay;
public Supervisor(String last, String first, String ID, double salary)
{
super(last, first, ID);
annualSalary = salary;
}
public void setAnnualSalary(double salary)
{
annualSalary = salary;
}
public double getAnnualSalary()
{
return annualSalary;
}
public double getMonthlyPay()
{
return ((annualSalary + (annualSalary * .02)) / 12);
}
public void increasePay(double percentage)
{
monthlyPay = monthlyPay* percentage;
}
public void decreasePay(double percentage)
{
monthlyPay = monthlyPay* percentage;
}
public String toString()
{
String result = "Name: " + getFirstName() + " " + getLastName() + "\nID: "
+ getIdNumber() + "\nAnnual Salary: " + annualSalary;
return result;
}
}
Output is:
4590.0
4590.0
2390.0
2390.0
Doesn't appear to be modifying getMonthlyPay()
Should be:
4590.00
4819.50
2390.00
2629.00
In increasePay, you are increasing monthlyPay:
public void increasePay(double percentage)
{
monthlyPay = monthlyPay* percentage;
}
But when you getMonthlyPay, you calculate the pay using two other variables - hourlyRate and hours:
public double getMonthlyPay()
{
return hourlyRate * hours;
}
So changing monthlyPay doesn't affect what getMonthlyPay returns. I suspect a similar thing happens in Supervisor.
increasePay should instead increase hourlyRate:
public void increasePay(double percentage)
{
hourlyRate *= 1 + percentage / 100;
}
Also, I don't think you need a monthlyPay field (or setMonthlyPay, for that matter) in HourlyEmployee at all. The monthly rate can always be calculated by hours and hourlyRate.
For Supervisor, do the same thing, and change annualSalary rather than monthlyPay:
public double getMonthlyPay()
{
return ((annualSalary + (annualSalary * .02)) / 12);
}
public void increasePay(double percentage)
{
annualSalary *= 1 + percentage / 100;
}
Hi guys i am fairly new to Java but ive come across a problem that i cant seem to fix, the problem is in the 'WashingMachine' Class its not displaying the 'spinSpeed' details , any answers will be appreciated
here are my codes:
enter code here
package test;
public class Client {
private String Name;
private String PhoneNo;
Client () {
Name = null;
PhoneNo= null;
}
Client (String N, String P){
Name = N;
PhoneNo = P;
}
public void setName(String N){
Name = N;
}
public void setPhoneNo(String P) {
PhoneNo = P;
}
public String getName(){
return Name;
}
public String setPhoneNo() {
return PhoneNo;
}
public String toString() {
return "\nName: "+ Name + "\nPhoneNo:"+ PhoneNo.toString();
}
}
enter code here
package test;
public class Machine {
private String Make;
private double Price;
private Client Cust;
public Machine(String make, double price, Client cust)
{
Make = make;
Price = price;
Cust = cust;
}
#Override
public String toString() {
return "\n" +"Make of machine: " + Make + "\n" + "Price: " + Price + "\n" + Cust.toString();
}
public String getMake() {
return Make;
}
public double getprice() {
return Price;
}
public Client getcust() {
return Cust;
}
}
enter code here
package test;
public class WashingMachine extends Machine {
private int spinSpeed;
public WashingMachine (String make, double price, Client cust, int spinSpeed){
super(make, price, cust);
}
#Override
public String toString() {
return "WashingMachine [spinSpeed=" + spinSpeed + ", spinSpeed()=" + spinSpeed() + "]";
}
public int spinSpeed() {
return spinSpeed;
}
enter code here
package test;
import java.util.ArrayList;
public class MachinePurchaseTestVerC {
public static void main(String [] args) {
ArrayList<Machine> gadgets = new ArrayList<Machine> ();
Client mCust2 = new Client("Paul", "0487654321");
Client mCust3 = new Client("Chandra", "0487651234");
Client wCust1 = new Client("Catherine", "0412345678");
Client wCust4 = new Client("Mike", "0412348756");
gadgets.add(new WashingMachine("Bosch", 549.50, wCust1, 3500));
gadgets.add(new Machine("Samsung", 678.50, mCust2));
gadgets.add(new Machine("Electrolux", 449.25, mCust3));
gadgets.add(new WashingMachine("LG", 500.00, wCust4, 3200));
for(int i = 0; i<gadgets.size(); i++){
System.out.println(gadgets.get(i).toString());
System.out.println("----------------------------------");
}
}
}
In your WashingMachine class, you forgot to set the speed in your constructor
public WashingMachine (String make, double price, Client cust, int spinSpeed){
super(make, price, cust);
this.spinSpeed = spinSpeed;
}
hope that helps :)
I've created a Java class called 'Book'. Using this class I'm willing to update information about a new object 'book1'. I'm also wanting to add Author information into the object 'book1'. So, I've dynamically allocated memory using a class-array called 'Author[ ]'. By this I mean there's a separate code in which I've created a class called 'Author' with its own set of instance variables. I'm not getting into that now. However, when I'm testing the class 'Book' using another class called 'TestBook' there's no compilation error BUT I'm getting the following message in the console window when I'm running the code:
Exception in thread "main" java.lang.NullPointerException
at Book.addAuthors(Book.java:34)
at TestBook.main(TestBook.java:12)
The code for 'Book' is shown below:
public class Book {
private String name;
private Author[] A = new Author[];
private int numAuthors = 0;
private double price;
private int qtyInStock;
public Book(String n, Author[] authors, double p) {
name = n;
A = authors;
price = p;
}
public Book(String n, Author[] authors, double p, int qIS) {
name = n;
A = authors;
price = p;
qtyInStock = qIS;
}
public Book(String n, double p, int qIS) {
name = n;
price = p;
qtyInStock = qIS;
}
public String getName() {
return name;
}
/*
public Author getAuthors() {
return A;
}
*/
public void addAuthors(Author newAuthor) {
A[numAuthors] = newAuthor; // THIS LINE IS WHERE THE ERROR POINTS TO
++numAuthors;
}
public void printAuthors() {
/*
for (int i = 0; i < A.length; i++) {
System.out.println(A[i]);
}
*/
for (int i = 0; i < numAuthors; i++) {
System.out.println(A[i]);
}
}
public void setPrice(double p) {
price = p;
}
public double getPrice() {
return price;
}
public void setqtyInStock(int qIS) {
qtyInStock = qIS;
}
public int getqtyInStock() {
return qtyInStock;
}
/*
public String getAuthorName() {
return A.getName();
}
public String getAuthorEmail() {
return A.getEmail();
}
public char getAuthorGender() {
return A.getGender();
}
*/
public String toString() {
/*
return getName() + " " + getAuthor() + " Book price: " + getPrice() +
" Qty left in stock: " + getqtyInStock();
*/
//return getName() + " is written by " + A.length + " authors.";
return getName() + " is written by " + numAuthors + " authors.";
}
}
The code for 'TestBook' is shown below:
public class TestBook {
public static void main(String args[]) {
//Author[] authors = new Author[2];
//authors[0] = new Author("Tapasvi Dumdam Thapashki", "tapasvi#thapashki.com", 'M');
//authors[1] = new Author("Paul Rand", "paulie#aol.com", 'M');
Book book1 = new Book("The Quickie Man", 69.00, 5);
//System.out.println(book1.toString());
//book1.setqtyInStock(5);
//System.out.println(book1.toString());
//System.out.println(book1.getAuthorName() + " " + book1.getAuthorEmail());
//book1.printAuthors();
book1.addAuthors(new Author("Linda Lee", "lindalee#grinchtown.com", 'F'));
book1.addAuthors(new Author("Joseph Caputo", "caputo#lfp.com", 'M'));
System.out.println(book1.toString());
book1.printAuthors();
}
}
The code for 'Author' is shown below:
public class Author {
private String name;
private String email;
private char gender;
public Author(String n, String e, char g) {
name = n;
email = e;
gender = g;
}
public String getName() {
return name;
}
public void setEmail(String e) {
email = e;
}
public String getEmail() {
return email;
}
public char getGender() {
return gender;
}
public String toString() {
return getName() + " [" + getGender() + "] " + getEmail();
}
}
I'd like some help with this.
Initialize Author array with proper size like private Author[] A = new Author[4];
You forgot to specify the size of the Array.
private Author[] A = new Author[15];
For making a dynamic array you can use ArrayList.
private ArrayList<Author> list = new ArrayList<Author>();
addAuthors()
public void addAuthors(Author newAuthor) {
list.add(newAuthor);
}
printAuthors()
public void printAuthors() {
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
i get three error message on my BookTest class and it says cannot find symbol on getCode(), getCategory, and calculateTax. how do i fix this? im trying to print these out in a dialog box but these three are the only ones not working.
import javax.swing. JOptionPane;
public class BookTest
{
public static void main(String args[])
{
double charge;
double grandTotal= 0;
String dataArray[][] = {{"NonFiction", "Abraham Lincoln Vampire Hunter","Grahame-Smith","978-0446563079","13.99","Haper","NY","US","Political"},
{"NonFiction", "Frankenstein","Shelley","978-0486282114","7.99","Pearson", "TX","England", "Historical"},
{"Fiction", "Dracula","Stoker","978-0486411095","5.99","Double Day", "CA","4918362"},
{"NonFiction", "Curse of the Wolfman"," Hageman","B00381AKHG","10.59","Harper", "NY","Transylvania","Historical"},
{"Fiction", "The Mummy","Rice","978-0345369949","7.99","Nelson","GA","3879158"}};
Book bookArray[] = new Book[dataArray.length];
int quantityArray[] = {12, 3, 7, 23, 5};
for (int i = 0; i < dataArray.length; i++)
{
if (dataArray[i][0] == "NonFiction")
{
bookArray[i] = new NonFictionBook(dataArray[i][1], dataArray[i][2], dataArray[i][3], Double.parseDouble(dataArray[i][4]),
new Publisher(dataArray[i][5], dataArray[i][6]), dataArray[i][7], dataArray[i][8]);
}
else
{
bookArray[i] = new FictionBook(dataArray[i][1], dataArray[i][2], dataArray[i][3], Double.parseDouble(dataArray[i][4]),
new Publisher(dataArray[i][5], dataArray[i][6]), Integer.parseInt(dataArray[i][7]));
}
}
String msg = "";
for (int i = 0; i < bookArray.length; i++)
{
charge = bookArray[i].calculateTotal(quantityArray[i]);
grandTotal = charge + grandTotal;
msg += String.format("%s %s %d $%.2f $%.2f\n", bookArray[i].getTitle(), bookArray[i].getCategory(), bookArray[i].getCode(), bookArray[i].calculateTax, charge); //this is where i get the 3 error messages. im trying to print all in one dialog box the title, category of the book, charge and tax for each book.
}
msg += String.format("Grand Total $%.2f ", grandTotal);
JOptionPane.showMessageDialog(null, msg);
}
}
**************************************************************
public abstract class Book implements Tax
{
private String title;
private String author;
private String isbn;
private Double price;
private Publisher publisher;
public Book()
{
setTitle("");
setAuthor("");
setIsbn("");
setPrice(0.0);
setPublisher(new Publisher());
}
public Book(String t, String a, String i, double p, Publisher n)
{
setTitle(t);
setAuthor(a);
setIsbn(i);
setPrice(p);
setPublisher(n);
}
public void setTitle(String t)
{
title = t;
}
public String getTitle()
{
return title;
}
public void setAuthor(String a)
{
author = a;
}
public String getAuthor()
{
return author;
}
public void setIsbn(String i)
{
isbn = i;
}
public String getIsbn()
{
return isbn;
}
public void setPrice(double p)
{
price = p;
}
public double getPrice()
{
return price;
}
public void setPublisher(Publisher n)
{
publisher = n;
}
public Publisher getPublisher()
{
return publisher;
}
public abstract double calculateTotal(int quantity);
public double calculateTax(double a)
{
return a * .08;
}
public String toString()
{
return( " Title " + title + " Author " + author + " Isbn " + isbn
+ " Price " + price + " Publisher " + publisher.toString());
}
}
********************************************************
public class NonFictionBook extends Book
{
private String country;
private String category;
public NonFictionBook()
{
super();
setCountry("");
setCategory("");
}
public NonFictionBook(String t, String a, String i, double p, Publisher n, String c, String ca)
{
super(t,a,i,p,n);
setCountry(c);
setCategory(ca);
}
public void setCountry(String c)
{
country = c;
}
public void setCategory(String ca)
{
category = ca;
}
public String getCountry()
{
return country;
}
public String getCategory()
{
return category;
}
public String toStirng()
{
return( super.toString() + "Country " + country + " Category " + category);
}
public double calculateTotal(int quantity)
{
double charge =0;
charge = (quantity * getPrice());
if( country != "US" )
charge += 50;
return charge;
}
}
*********************************************
public class FictionBook extends Book
{
private int code;
public FictionBook()
{
super();
setCode(0);
}
public FictionBook(String t, String a, String i, double p, Publisher n, int c)
{
super(t,a,i,p,n);
setCode(c);
}
public void setCode(int c)
{
code = c;
}
public int getCode()
{
return code;
}
public String toString()
{
return (super.toString() + " Code " + code);
}
public double calculateTotal(int quantity)
{
double charge =0;
charge = (quantity * getPrice());
if (quantity > 5)
charge += 5 * (quantity - 5);
return charge;
}
}
The tree methods are implemented in subclasses of Books. So you have to cast the value to the subclass.
if (bookArray[i] instanceof FictionBook){
FictionBook fb = (FictionBook)bookArray[i];
msg += String.format("%s %s %d $%.2f $%.2f\n", fb.getTitle(), "", fb.getCode(), 0, charge);
}
if (bookArray[i] instanceof NonFictionBook){
NonFictionBook fb = (NonFictionBook)bookArray[i];
msg += String.format("%s %s %d $%.2f $%.2f\n", nfb.getTitle(), nfb.getCategory(), nfb.getCode(), nfb.calculateTax, charge);
}
and so on
Also you have to use equals() for comparing string. Not ==
In the line you get error you try to print fields that are not instances of the Book class but of its subclasses.
You got an array of Books, you iterate on them and try to print the information. But not all the Books have getCode() method (only the fiction books) and only the non fiction books have getCategory() method. So you can't do this for ALL books.
You can change your print depending on the book type or you can make a method in Book class and each subclass can override it that prints the information you have for this class (like the toString method). Then use that in the main class.
And also as pointed in comments test if strings are equal with equals operator and not == or !=
Your array uses the type book:
Book bookArray[] = new Book[dataArray.length];
Later, you add sub-classes into this array, like NonFictionBook. Since code, category etc. are only part of the sub-classes, you cannot access them using the Book array reference.
// won't work because class Book does not have these methods, properties
bookArray[i].getCategory(), bookArray[i].getCode(), bookArray[i].calculateTax
You need to cast the object (based on what type is in the array).
I have this main java file:
public class GroceryBill {
private Employee clerk;
private List<Item> receipt;
private double total;
private double internalDiscount;
public GroceryBill(Employee clerk) {
this.clerk = clerk;
receipt = new ArrayList<Item>();
total = 0.0;
internalDiscount = 0.0;
}
public void add(Item i) {
receipt.add(i);
total += i.getPrice();
internalDiscount += i.getDiscount();
}
public double getTotal() {
return Math.rint(total * 100) / 100.0;
}
public Employee getClerk() {
return clerk;
}
public void printReceipt() {
System.out.println(this);
}
private String valueToString(double value) {
value = Math.rint(value * 100) / 100.0;
String result = "" + Math.abs(value);
if(result.indexOf(".") == result.length() - 2) {
result += "0";
}
result = "$" + result;
return result;
}
public String receiptToString() {
String build = "items:\n";
for(int i = 0; i < receipt.size(); i++) {
build += " " + receipt.get(i);
if(i != receipt.size() - 1) {
build += "\n";
}
}
return build;
}
public String toString() {
return receiptToString() + "\ntotal: " + valueToString(total);
}
public String discountToString() {
return receiptToString() + "\nsub-total: " + valueToString(total) + "\ndiscount: " + valueToString(internalDiscount) + "\ntotal: " + valueToString(total - internalDiscount);
}
public static class Employee {
private String name;
public Employee(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
public static class Item {
private String name;
private double price;
private double discount;
public Item(String name, double price, double discount) {
this.name = name;
this.price = price;
this.discount = discount;
}
public double getPrice() {
return price;
}
public double getDiscount() {
return discount;
}
private String valueToString(double value) {
String result = "" + Math.abs(value);
if(result.indexOf(".") == result.length() - 2) {
result += "0";
}
result = "$" + result;
return result;
}
public String toString() {
return name + " " + valueToString(price) + " (-" + valueToString(discount) + ")";
}
}
// REPLACEME
}
I want to call and be able to use getDiscount() and etc from the "Item" subclass, but I can't figure out how to access it in a different file + class that extends GroceryBill.
public class DiscountBill extends GroceryBill {
private int myCount;
private double myDiscount;
private double myPrice;
private String myName;
public DiscountBill(Employee clerk, boolean preferred) {
super(clerk);
String name = "";
double price = 0;
double discount = 0;
GroceryBill.Item myBill = new GroceryBill.Item(name, price, discount);
Object myItem = new Item(name, price, discount);
myDiscount = myBill.getDiscount();
myPrice = ((GroceryBill.Item) myItem).getPrice();
if (preferred && myDiscount > 0.0) {
myCount++;
}
}
public int getDiscountCount() {
return myCount;
}
public double getDiscountAmount() {
return myDiscount;
}
public double getDiscountPercent() {
return (myPrice / getDiscountCount()) * 100;
}
}
Here is my class that is in a different java file that extends the original one. How would I call methods from the Item subclass that belongs to the GroceryBill class?
You can do like
Create object to super class using that object try to create object for its sub class.
for example:
public class Sample {
class InnerClass
{
public void foo()
{
System.out.println("Helolo");
}
}
}
Base class is :
public class BaseClass extends Sample {
public static void main(String[] args) {
Sample sObj = new Sample();
Sample.InnerClass innerObj = sObj.new InnerClass();
innerObj.foo();
}
}
You can follow this approach to call inner class methods
To access inner static classes :
OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
In your case just add statement like :
GroceryBill.Item = new GroceryBill.Item(name, price, discount);