In my BOOKING class I have this method to calculate the total amount
public void calcTotal(){
total = amount*priceperbooking;
}
I created a subclass called BOOKING_APPLICATION and I want to override the calcTotal() method if amount > 5 then it must subtract 15% of the total
Here is what I tried but it does not work:
public void calcTotal(){
if (super.amount>5) {
super.total = super.total-(15/100.0*super.total);
}
}
When I run it its giving me the original total, not taking out 15%
What am I doing wrong
Edit: Here is the code of my main class
public class Diving_Adventures{
static BOOKING obj1 = new BOOKING();
static BOOKING_APPLICATION obj2 = new BOOKING_APPLICATION();
public static void main(String[] args) {
obj1.setName();
obj1.setNumber();
obj1.setAmount();
obj1.setPriceperbooking();
obj1.calcTotal();
obj2.calcTotal();
JOptionPane.showMessageDialog(null, obj1.toString());
}
}
I'm assuming by obj1.calcTotal() it will calculate the total and by obj2.calcTotal it will take out the 15% but it does not work
Here is the full code of my BOOKING class:
private String name;
private int number;
public int amount;
public double priceperbooking;
public double total;
public String getName() {
return name;
}
public int getNumber() {
return number;
}
public int getAmount() {
return amount;
}
public double getPriceperbooking() {
return priceperbooking;
}
public void setName() {
this.name = JOptionPane.showInputDialog("Enter the name");;
}
public void setNumber() {
this.number = Integer.parseInt(JOptionPane.showInputDialog("Enter the number"));
}
public void setAmount() {
this.amount = Integer.parseInt(JOptionPane.showInputDialog("Enter the amount"));
}
public void setPriceperbooking() {
this.priceperbooking = Double.parseDouble(JOptionPane.showInputDialog("Enter the price per bookin"));;
}
public void calcTotal(){
total = amount*priceperbooking;
}
#Override
public String toString() {
return "Customer name: "+name+"\n"+"number"+ number + "\namount=" + amount +
"\n priceperbooking=" + priceperbooking + "\n total=" + total ;
}
In your derived class:
public void calcTotal() {
total = super.calcTotal();
if (amount > 5) {
total = total - (15/100.0 * total);
}
}
You are mising on calculating the total first, as mentioned.
Related
-----ATM.java-----
public class ATM {
int cash;
boolean inService;
public ATM() {
cash = 0;
inService = false;
}
public ATM(int x, boolean y) {
cash = x;
inService = y;
}
public int queryCash() {
return cash;
}
public void increaseCash(int x) {
cash = cash + x;
}
public void reduceCash(int x) {
cash = cash - x;
}
public boolean getServiceStatus() {
return inService;
}
public void changeServiceStatus() {
if (inService) {
inService = false;
System.out.println("inService is now false");
}
else {
System.out.println("inService is now true");
}
}
public class CashDispenser {
public void dispenseCash(int x) {
reduceCash(x);
System.out.println(x + " dollars has been dispensed.");
}
}
CashDispenser dispenser = new CashDispenser();
public class ReceiptPrinter {
public void printReceipt() {
System.out.println("Receipt has been printed.");
}
}
ReceiptPrinter printer = new ReceiptPrinter();
public class CardReader{
public void readCard() {
System.out.println("Card has been read.");
}
}
CardReader reader = new CardReader();
public class KeypadDisplay{
public void displayPINverification() {
System.out.println("PIN has been verified.");
}
}
KeypadDisplay display = new KeypadDisplay();
}
------Person.java-------
public class Person {
String name;
public Person(){
name = "default";
}
public String getName() {
return name;
}
public void setName(String nameString) {
name = nameString;
System.out.println("The name is set to "+ name);
}
}
--------Operator.java------
public class Operator extends Person {
public void topUpATM(ATM atm) {
System.out.println("Current inService is "+ atm.inService);
System.out.println("Current cash is "+ atm.cash);
if (atm.getServiceStatus() == true){
atm.changeServiceStatus();
System.out.println("ATM now has "+ atm.queryCash()+" dollars.");
atm.changeServiceStatus();
}
if (atm.queryCash() < 5000){
atm.increaseCash(5000);
System.out.println("ATM now" + atm.queryCash()+ " dollars.");
atm.changeServiceStatus();
}
}
}
---------Customer.java-------- **I dont know what am i doing wrong over here as this is the place where getserviceStatus() should return true but it is returning false. Other functions work perfectly so far but I am stuck on this issue for quite a while now and I cannot figure it out why is it that way. **
public class Customer extends Person {
public void withdrawCash(ATM atm, int amount) {
//atm.changeServiceStatus();
System.out.println("Current inService is "+atm.getServiceStatus());
if (!atm.getServiceStatus()) {
System.out.println("ATM is not in service.");
}
else if (atm.queryCash()<amount) {
System.out.println("ATM has insufficient cash");
}
else {
atm.reader.readCard();
atm.display.displayPINverification();
atm.dispenser.dispenseCash(amount);
atm.printer.printReceipt();
System.out.println(amount+" successfully withdrawn from ATM");
}
}
}
----------------A00.java------------
import java.util.Scanner;
public class A00 {
public static void main (String [] args) {
Scanner input = new Scanner(System.in);
int Number;
System.out.println("Please enter between 0 and 10,000");
Number = input.nextInt();
ATM atm_1 = new ATM (0,false);
ATM atm_2 = new ATM (Number,true);
input.nextLine();
System.out.println("Please enter a name for the operator");
String name = input.nextLine();
Operator operate = new Operator();
operate.setName(name);
System.out.println("Processing ATM 1");
operate.topUpATM(atm_1);
System.out.println("Processing ATM 2");
operate.topUpATM(atm_2);
Customer cust = new Customer();
String customer;
System.out.println("Enter the name of a customer:");
customer = input.nextLine();
cust.setName(customer);
System.out.println("Please enter the amount you want to withdraw: ");
int withdraw;
withdraw = input.nextInt();
cust.withdrawCash(atm_1, withdraw);
input.close();
}
}
You recall the method withdrawCash passing atm_1 as parameter and atm_1 is istantiated as ATM atm_1 = new ATM (0,false);
The second parameter in ATM constructor sets inService = false
Ok so basically this is my program it's about Students & Student Groups;
Each student has a name, ID and marks/points;
The program is working fine but what's missing is that the SUM function in the class StudentsGroup needs to be static and to take a parameter of the "Group" of which you need the sum of points. My problem is that when I put the function and the ArrayList to static, the function returns both of the groups score combined and I don't know how to make it work
//the program works correctly and returns the correct values about
everything; i only get those errors when i try to change the
sumOfPoints function to static
the two files that i have are:
Group 1:
61662126 Laurel 50
61662213 Mark 35.5
61662345 Yanny 67
61662127 Larry 27
61662125 Kevin 87.5
and Group 2:
61662126 Jason 70
61662213 Josh 25.5
61662345 Bobby 57
61662127 Megan 17
61662125 Drake 86.5
the correct output should be:
Total points of Group1: 267.0
Total points of Group2: 256.0
Comparing Group1 to Group2: 1
but when i put it to static it returns 523 in both which is both of the groups combined and i don't understand what im doing wrong
public interface IFile
{
public void Load();
}
public class Student implements Comparable<Student>
{
private int facnum;
private String name;
private double points;
public Student(int fn, String n, double p)
{
this.facnum = fn;
this.name = n;
this.points = p;
}
public void SetFN(int fn)
{
this.facnum = fn;
}
public void SetName(String n)
{
this.name = n;
}
public void SetPoints(double p)
{
this.points = p;
}
public int GetFN()
{
return this.facnum;
}
public String GetName()
{
return this.name;
}
public double GetPoints()
{
return this.points;
}
public boolean equals(Object s)
{
if (this.GetFN() != ((Student)s).GetFN())
{
return false;
}
return true;
}
public int compareTo(Object s)
{
if(this.GetFN() < ((Student)s).GetFN())
{
return -1;
}
if(this.GetFN() > ((Student)s).GetFN())
{
return 1;
}
return 0;
}
public String toString()
{
return "Faculty Number: " + this.facnum + " Name: " + this.name + " Points: " + this.points + " \n";
}
}
import java.io.*;
import java.util.*;
public class StudentsGroup implements IFile, Comparable<Object>
{
private String groupname;
private List<Student>oStudent = new ArrayList<Student>();
public StudentsGroup(String filename)
{
this.groupname = filename;
Load();
}
public void Load(){
try
{
Scanner sc=new Scanner(new File(this.groupname));
while(sc.hasNextLine())
{
oStudent.add(new Student(sc.nextInt(),sc.next(),
sc.nextDouble()));
}
sc.close();
}
catch(IOException e)
{
System.out.println("Input/Output Error...");
}
}
public void printColl()
{
System.out.println(oStudent.toString());
}
public List<Student> sortedListFN()
{
Collections.sort(oStudent);
return oStudent;
}
public double sumOfPoints()
{
double sum = 0.00;
for(Iterator<Student> it= oStudent.iterator(); it.hasNext();)
{
Student c = it.next();
sum += c.GetPoints();
}
return sum;
}
public int compareTo(Object s)
{
if(this.sumOfPoints() < ((StudentsGroup) s).sumOfPoints())
{
return -1;
}
if(this.sumOfPoints() > ((StudentsGroup) s).sumOfPoints())
{
return 1;
}
return 0;
}
public static void main(String[] args)
{
StudentsGroup oGroup1 = new StudentsGroup("Group1.txt");
oGroup1.printColl();
System.out.println("Sorted order by FN: " + oGroup1.sortedListFN() + "\n");
StudentsGroup oGroup2 = new StudentsGroup("Group2.txt");
System.out.println("Total points of Group1: " + oGroup1.sumOfPoints() + "\n");
System.out.println("Total points of Group2: " + oGroup2.sumOfPoints() + "\n");
System.out.println("Comparing Group1 to Group2: " + oGroup1.compareTo(oGroup2));
}
}
edit//the static method that i tried is changing oStudent to static:
private static List<Student>oStudent = new ArrayList<Student>();
obviously changing the sum function to static & editing the compareTo method:
public static double sumOfPoints(Object s)
{
double sum = 0.00;
s = new ArrayList<Student>(oStudent);
for(Iterator<Student> it= ((List<Student>) s).iterator(); it.hasNext();)
{
Student c = it.next();
sum += c.GetPoints();
}
return sum;
}
public int compareTo(Object s)
{
if(this.sumOfPoints(this) < ((StudentsGroup) s).sumOfPoints(s))
{
return -1;
}
if(this.sumOfPoints(this) > ((StudentsGroup) s).sumOfPoints(s))
{
return 1;
}
return 0;
}
and the output:
System.out.println("Total points of Group1: " + oGroup1.sumOfPoints(oGroup1) + "\n");
System.out.println("Total points of Group2: " + oGroup2.sumOfPoints(oGroup2) + "\n");
System.out.println("Comparing Group1 to Group2: " + oGroup1.compareTo(oGroup2));
and the output starts returning 523
Your static method overwrites s with the inner object of that particular instance class:
s = new ArrayList<Student>(oStudent);
I think your mistake is here. This is not how you use a static method of class. The correct way to do it is StudentsGroup.sumOfPoints(yourObjectHere). A static method should not know about any field of a particular instance.
Im trying to create a small character builder, using inheritance. i have CreateCharacter CharacterRace then a Dwarf class. i made a variable with type CharacterRace in CreateCharacter and a variable with type Dwarf in CharacterRace. i have an object of CreateCharacter in my main method demo and its not letting me call the methods from the Dwarf class, to make a dwarf character. im thinking ineed to pass a dwarf object in characterRace? im just not sure how. heres my code: (its a bit long my apologies)
package characterCreation;
public class CreateCharacter {
private CharacterClass characterClass;
private CharacterRace characterRace;
private Name name;
public CreateCharacter(String characterName,CharacterClass characterClass,CharacterRace characterRace) {
this.name = new Name(characterName);
this.characterClass = characterClass;
this.characterRace = characterRace;
}
public CreateCharacter(){
}
public CharacterClass getCharacterClass() {
return characterClass;
}
public void setCharacterClass(CharacterClass characterClass) {
this.characterClass = characterClass;
}
public CharacterRace getCharacterRace() {
return characterRace;
}
public void setCharacterRace(CharacterRace characterRace) {
this.characterRace = characterRace;
}
public Name getName(){
return name;
}
public void setName(Name name){
this.name = name;
}
#Override
public String toString() {
return "CreateCharacter [name=" + name + ", characterRace=" + characterRace + ", characterClass="
+ characterClass + "]";
}
}
package characterCreation;
public class CharacterRace {
protected String raceName;
protected double mana;
protected double hp;
private Dwarf dwarf;
public CharacterRace(String raceName,double mana, double hp) {
this.raceName = raceName;
this.mana = mana;
this.hp = hp;
}
public CharacterRace(){
}
public String getRaceName() {
return raceName;
}
public Dwarf getDwarf() {
return dwarf;
}
public void setDwarf(Dwarf dwarf) {
this.dwarf = dwarf;
}
public double getMana() {
return mana;
}
public double getHp() {
return hp;
}
#Override
public String toString() {
return "CharacterRace [dwarf=" + dwarf + "]";
}
}
package characterCreation;
public class Dwarf extends CharacterRace {
public Dwarf(String raceName,double mana, double hp) {
super(raceName,mana,hp);
}
public double getMana() {
mana = 5;
return mana;
}
public double getHp() {
hp = 10;
return hp;
}
public String getRaceName(){
return raceName = "Dwarf";
}
#Override
public String toString() {
return "Dwarf [mana=" + mana + ", hp=" + hp + ", getRaceName()=" + getRaceName() + "]";
}
}
package characterCreation;
import java.util.Scanner;
public class CharacterDemo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
CreateCharacter create = new CreateCharacter();
System.out.println("Choose your Race: ");
String userRace = input.next();
create.setName(new Name("Daxel"));
//create.setCharacterRace(race);
System.out.println(create.getName());
//Dwarf dwarf = new Dwarf();
System.out.println(create.getCharacterRace().getDwarf().getRaceName());
//System.out.println(create.getCharacterRace().setDwarf(new Dwarf("dwarf",10,5)));
}
}
You have to call setCharacterRace() on create; then call setDwarf() on the characterRace; otherwise create.getCharacterRace() would be null and create.getCharacterRace().getDwarf() would throw NullPointerException.
I don't understand the logic behind your code, but try the code below:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
CreateCharacter create = new CreateCharacter();
System.out.println("Choose your Race: ");
String userRace = input.next();
create.setName(new Name("Daxel"));
//***********new code starts******
CharacterRace myRace = new CharacterRace(userRace, 20, 9);
myRace.setDwarf(new Dwarf("dwarf",10,5));
create.setCharacterRace(myRace);
//***********new code ends********
//create.setCharacterRace(race);
System.out.println(create.getName());
//Dwarf dwarf = new Dwarf();
System.out.println(create.getCharacterRace().getDwarf().getRaceName());
//System.out.println(create.getCharacterRace().setDwarf(new Dwarf("dwarf",10,5)));
}
So I am working on this Payroll class, I need to create two employees, hours worked and hourly pay and the calculate salaries. Finally, I have to add 10 extra hours to one of the previously created employees and calculate and display the total payroll. I wrote the two classes and everything works perfect, but when I look at the total Payroll it does not take into consideration the added hours.
The output for totalPayRoll should be $2000 after increasing the hours but i still get $1750!
public class PayRoll {
static double getTotalPayRoll()
{
return TotalPayRoll;
}
public String employeeId;
public int hoursWorked;
public final double hourlyPay;
private static double TotalPayRoll;
private static double Salary;
public PayRoll (String theEmployeeId, int theHoursWorked,
double theHourlyPay)
{
this.employeeId = theEmployeeId;
this.hoursWorked = theHoursWorked;
this.hourlyPay = theHourlyPay;
Salary = hoursWorked*hourlyPay;
TotalPayRoll = TotalPayRoll + Salary ;
}
public String getTheEmployeeId()
{
return this.employeeId;
}
public int getTheHoursWorked()
{
return this.hoursWorked;
}
public double getTheHourlyPay()
{
return this.hourlyPay;
}
public double getSalary()
{
return PayRoll.Salary;
}
public void increase (int extraHours)
{
hoursWorked = (hoursWorked + extraHours);
}
public void changeTheHoursWorked (int amount)
{
hoursWorked = hoursWorked + amount;
}
public void calculateSalary()
{
Salary = hoursWorked*hourlyPay;
}
public void calculateTotalPayRoll()
{
TotalPayRoll= TotalPayRoll+Salary;
}
public void changeHours(int newHours)
{
hoursWorked = newHours;
}
}
And this is the main
public class Test {
public static void main(String[] args) {
// TODO code application logic here
Date d = new Date();
DateFormat df = DateFormat.getDateInstance( DateFormat.MEDIUM );
NumberFormat nf = NumberFormat.getCurrencyInstance();
System.out.println("\nPayroll For Week Ending " + df.format(d));
System.out.println("-------------------------------------");
PayRoll employee1 = new PayRoll("444-4444", 30, 25);
employee1.calculateSalary();
displaySalary(employee1, nf);
PayRoll employee2 = new PayRoll("555-5555", 20, 50);
employee2.calculateSalary();
displaySalary(employee2, nf);
System.out.println("Increase " + employee1.getTheEmployeeId() +
" by 10 hours");
employee1.changeTheHoursWorked(10); // 10 hours increase
employee1.calculateSalary();
displaySalary(employee1, nf);
System.out.println("Total payout amount.. " +
nf.format(PayRoll.getTotalPayRoll()));
}
public static void displaySalary(PayRoll e, NumberFormat nf)
{
System.out.println("Employee #: " + e.getTheEmployeeId());
System.out.println("Hours Worked: " + e.getTheHoursWorked());
System.out.println("Hourly Rate: " + e.getTheHourlyPay());
System.out.println("Your Salary is: " + e.getSalary());
System.out.println("---------------------------------\n");
}
}
In your class :
private static double TotalPayRoll;
private static double Salary;
Both are static members(class level members), so there will be only one copy of these members which will be shared among all the objects. Because TotalPayRoll and salary should be different for different payrolls so these should be non-static.
This is because you have static fields - make everything non-static
private static double TotalPayRoll; -> private double TotalPayRoll;
private static double Salary; -> private double Salary;
What is happening with static fields is
Firstly hoursWorked is set to 30
then
hoursWorked is set to 20
then
hoursWorked is increased by 10
Since you are declaring objects of your PayRoll class, you don't need to make an static members.
You can make your class like this
public class PayRoll {
//don't have to declare any member public since you have functions to return value
//don't need access specifier since they are private by default
String employeeId;
int hoursWorked;
double hourlyPay;
double TotalPayRoll=0; //you have to initialize it to zero
double Salary;
public PayRoll (String theEmployeeId, int theHoursWorked,
double theHourlyPay)
{
this.employeeId = theEmployeeId;
this.hoursWorked = theHoursWorked;
this.hourlyPay = theHourlyPay;
// Salary = hoursWorked*hourlyPay;
// TotalPayRoll = TotalPayRoll + Salary ;
//you do not need to do this since you have different functions for them
}
public double getTotalPayRoll()
{
return this.TotalPayRoll;
}
public String getTheEmployeeId()
{
return this.employeeId;
}
public int getTheHoursWorked()
{
return this.hoursWorked;
}
public double getTheHourlyPay()
{
return this.hourlyPay;
}
public double getSalary()
{
return this.Salary;
}
//don't need the increase method
public void changeTheHoursWorked (int amount)
{
hoursWorked += amount;
}
public void calculateSalary()
{
Salary = hoursWorked*hourlyPay;
}
public void calculateTotalPayRoll()
{
TotalPayRoll+=Salary;
}
//don't need the change hours function
}
Hope this helps :)
I am trying to rewrite the toString() to print names. I use getNm() from each employee in an arraylist of object employees. Employees have the parameters (pay, nm, hoursWorked, overtimeHours)
I have bolded the code I am focused on.
public class Main {
public static void main(String[] args){
workers workerlist = new workers();
workerlist.setNumberEmployees();
workerlist.instantiateEmployees();
System.out.println(workerlist.toString());
}
}
public class Employees extends workers{
public double pay;
public String nm;
public double hours;
public double overtime;
public Employees(double pay, String nm, double hoursWorked, double overtimeHours){
}
public double getPay(){
return pay;
}
public void setPay(double pay){
}
public String getNm(){
return nm;
}
public void setNm(String nm){
}
public double getHours(){
return hours;
}
public void setHours(double hours){
}
public double getOvertime(){
return overtime;
}
public void setOvertime(double overtime){
}
}
import java.util.ArrayList;
import java.util.Scanner;
public class workers{
public int employeenumber;
public String nm;
ArrayList<Employees> workerList = new ArrayList<Employees>();
Scanner input = new Scanner(System.in);
public void setNumberEmployees(){
System.out.println("How many employees do you have?");
employeenumber = input.nextInt();
}
public int getNumberEmployees(){
return employeenumber;
}
public void instantiateEmployees(){
for(int i=1; i<=employeenumber; i++){
workerList.add(new Employees(0.0, "nm", 0.0, 0.0));
}
}
public String toString(){
String st = "";
for(int i=0; i<employeenumber; i++){
**st += workerList.toString();**
// ".toString() is there to test the setting of parameters, I am interested in replacing this part.
}
return st;
}
}
Expected Output [Employee 1's name, Employee 2's name,... Employee n's name]
I think below code will give your expected result.
public class Main {
public static void main(String[] args) {
workers workerlist = new workers();
workerlist.setNumberEmployees();
workerlist.instantiateEmployees();
System.out.println(workerlist.toString()); //call toString to take workerlist
}
}
Override Employees toString method and do not forget update nm parameter in constructor
public class Employees extends workers {
public double pay;
public String nm;
public double hours;
public double overtime;
public Employees(double pay, String nm, double hoursWorked, double overtimeHours) {
this.nm = nm; //do not forget set value
}
public double getPay() {
return pay;
}
public void setPay(double pay) {
}
public String getNm() {
return nm;
}
public void setNm(String nm) {
}
public double getHours() {
return hours;
}
public void setHours(double hours) {
}
public double getOvertime() {
return overtime;
}
public void setOvertime(double overtime) {
}
#Override
public String toString() {
return getNm(); //Employees toString method will return nm
}
}
override toString method and call arraylist's toString method.
public class workers {
public int employeenumber;
public String nm;
ArrayList<Employees> workerList = new ArrayList<Employees>();
Scanner input = new Scanner(System.in);
public void setNumberEmployees() {
System.out.println("How many employees do you have?");
employeenumber = input.nextInt();
}
public int getNumberEmployees() {
return employeenumber;
}
public void instantiateEmployees() {
for (int i = 1; i <= employeenumber; i++) {
workerList.add(new Employees(0.0, "nm", 0.0, 0.0));
}
}
public String toString() {
return workerList.toString(); //no need to iterate on arraylist, Arraylist.toString method will call each Employees toString method.
}
}
Yusuf K. and Andrew Tobilko have answered your question correctly. Just to give you some hints to improve your classes a bit:
Why do you call Employees eventhough your class can represent a single employee; so I would call it Employee instead.
Why do you define the nm field twice? It is declared in Workers class from which the Employees class is derived.
setNumberEmployees() method does not comply with JavaBeans convention; it must be declared as
public void setNumberEmployees(final String noEmployees) {
employeenumber = noEmployees;
}
And the call to setNumberEmployees() should be done in the main() method as
public static void main(String[] args){
workers workerlist = new workers();
Scanner input = new Scanner(System.in);
workerlist.setNumberEmployees(input.nextInt());
workerlist.instantiateEmployees();
System.out.println(workerlist.toString());
}
And lastly, you are speaking about parameter(s). They are actually called fields or instance variable(s).
public String toString(){
String st = "";
for(int i=0; i < employeenumber; i++)
st += workerList.get(i).toString();
return st;
}
But this solution is not the best. I suggest you the next one:
public String toString(){
StringBuilder builder = new StringBuilder();
workerList.stream().map(Employees::toString).forEach(builder::append);
return builder.toString();
}
And, of course, you have to override toString() in the Employees class. For example,
#Override public String toString() {
return new StringJoiner(", ")
.add(Double.toString(pay))
.add(nm)
.add(Double.toString(hours))
.add(Double.toString(overtime))
.toString();
}