The problem I am dealing with is that I can't figure out how to make certain values in my class appear which they only return as zeros. I'm a beginner so I don't know much about Java but I have to make 4 classes or 3 types of employees and one class to output their values. But I can't get the values for the commission and union employ to show. Here is the code:
import java.util.Scanner;
// Base or Superclass
class Employee
{
String name;
String department;
double pay;
double hours;
double money;
double mission;
double rate;
double withheld;
double moneyc;
double moneyu;
double sales;
public void inputs()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter your name: ");
name = in.nextLine();
System.out.println("Enter your department: ");
department = in.nextLine();
System.out.println("Enter your pay per hour: ");
pay = in.nextDouble();
System.out.println("Enter how many hours you worked: ");
hours = in.nextDouble();
System.out.println("Enter your rate of commission(0.00): ");
rate = in.nextDouble();
System.out.println("Enter your withheld amount: ");
withheld = in.nextDouble();
System.out.println("Enter your sales amount: ");
sales = in.nextDouble();
money = pay * hours;
}
// Accessor Methods
public String getName()
{
return this.name;
}
public String getDepartment()
{
return this.department;
}
public Double getPay()
{
return this.pay;
}
public Double getHours()
{
return this.hours;
}
public Double getMoney()
{
return this.money;
}
public Double getMission()
{
return this.mission;
}
public Double getRate()
{
return this.rate;
}
public Double getWithheld()
{
return this.withheld;
}
public Double getMoneyc()
{
return this.moneyc;
}
public Double getMoneyu()
{
return this.moneyu;
}
public Double getSales()
{
return this.sales;
}
// Mutator Methods
public void setName(String n)
{
name = n;
}
public void setDepartment(String d)
{
department = d;
}
public void setPay(double p)
{
pay = p;
}
public void setHours(double h)
{
hours = h;
}
public void setMoney(double m)
{
money = m;
}
public void setMission(double mi)
{
mission = mi;
}
public void setRate(double r)
{
rate = r;
}
public void setWithheld(double w)
{
withheld = w;
}
public void setMoneyc(double mc)
{
moneyc = mc;
}
public void setMoneyu(double mu)
{
moneyu = mu;
}
public void setSales(double s)
{
sales = s;
}
}
class Last extends Employee
{
public void dinero()
{
Employee one = new Employee();
one.inputs();
// Union Employee
UnionEmployee three = new UnionEmployee();
three.Syndicate();
// Commission Employee
Commissioned two = new Commissioned();
two.sales();
System.out.println("\n"+ "Name: "+ one.getName());
System.out.println( "Department: "+ one.getDepartment());
System.out.println( "Hours: "+ one.getHours());
System.out.println( "Pay Rate: "+ one.getPay());
System.out.println("Your money is: "+ one.getMoney());
// Commissioned Employee
System.out.println( "\n"+ "Commissioned Employee");
System.out.println("Your money is: "+ one.getMoneyc());
System.out.println( "Your commission is: "+ one.getMission());
System.out.println("Your rate: "+ one.getRate());
// Union employee
System.out.println("\n"+"Union Employee");
System.out.println("Your money is: "+ one.getMoneyu());
System.out.println( "Your withheld is: "+ one.getWithheld());
}
}
// Derived or Subclass
class Commissioned extends Employee
{
public void sales()
{
moneyc = hours * pay;
// Commission
mission = sales * rate;
}
}
// Derived or Subclass
class UnionEmployee extends Employee
{
public void Syndicate()
{
if (hours <= 40) {
moneyu = (hours * pay) - withheld;
} else {
moneyu = (pay * hours * ((hours - 40) * 1.5)) - withheld;
}
}
}
public class WeiTry extends Last
{
public static void main(String[] args)
{
// Output
Last show = new Last();
show.dinero();
}
}
The only place I see your Employee's fields get set is inside a method called inputs()
one's values get populated because you call the inputs method on one but for your other employee types like your UnionEmployee three, inputs never called, and their fields never get set.
If you want your other employee's values to get set, it looks like you'll have to call their inputs method.
UnionEmployee three = new UnionEmployee();
three.inputs();
three.Syndicate();
or you can just copy them over
three.setName(one.getName());
Related
How do I add the public method priceAfterDiscount which returns the price after discount in this class:
public class Book1 {
private String title;
private double price;
public static final double DISCOUNT=0.20;
public Book1(){
title="Unkown";
price=0.0;
}
public Book1(String name, double cost){
title=name;
price=cost;
}
public void setTitle(String n){
title=n;
}
public String getTitle(){
return title;
}
public void setPrice(double p){
price=p;
}
public double getPrice(){
return price;
}
}
public double priceAfterDiscount() {
if (price <= 0) {
return 0;
}
return price - (price * DISCOUNT);
}
public String toString() {
return title + " " + priceAfterDiscount();
}
Here is my main activity. Help me write the code.
import java.util.Scanner;
public class BookStore {
static Scanner console= new Scanner(System.in);
public static void main(String[]args){
Book1 b1,b2;
String title;
double price,newPrice;
System.out.print("Enter title: ");
title=console.next();
System.out.print("Enter price: ");
price=console.nextDouble();
/*
Create a book object based on the user input for b1
Call method priceAfterDiscount to get b1's new price
Print b1's information including title, price and newPrice*/
System.out.print("Enter another title: ");
title=console.next();
System.out.print("Enter another price: ");
price=console.nextDouble();
/*Create a book object based on the user input b2*/
if( ){ /*Compare the original prices of b1 and b2 have the same original price*/
System.out.println("Same price");
}
else{
System.out.println("Not Same Price");
}
Add $10 to b1's original price (hard code)
}
}
This should work:
public double priceAfterDiscount() {
if (price <= 0) {
return 0;
}
return price - (price * DISCOUNT);
}
public String toString() {
return title + " " + priceAfterDiscount();
}
If i wanted to use a Dynamic Array List which is initializing class Worker can i add sub-classes that extend the Worker class and try to fill them with data like the following test class?.. whenever i try calling a certain function that one of the sub-classes have i get an error , I need to call these functions so how can i do it correctly?
public class Worker extends Person {
private int id;
Worker() {
}
Worker(int i) {
id = i;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String toString() {
return super.toString() + "ID: " + id + " ";
}
}
public class HourlyWorker extends Worker implements Annual {
private double rate;
private double AnnualPayment;
private double percentageIncrease;
HourlyWorker() {
}
HourlyWorker(double r) {
rate = r;
}
public double getAnnualPay(double Annualpayment) {
return Annualpayment = rate * 52 * 40;
}
public double getRate() {
return rate;
}
public void setRate(double rate) {
this.rate = rate;
}
public double getAnnualPayment() {
return AnnualPayment;
}
public void setAnnualPayment(double AnnualPayment) {
this.AnnualPayment = AnnualPayment;
}
public double getpercentageIncrease() {
return percentageIncrease;
}
public void setpercentageIncrease(double percentageIncrease) {
this.percentageIncrease = percentageIncrease;
}
public void increasePayment(double r) {
increasePayR(r);
}
public double increasePayR(double r) {
return rate = (AnnualPayment + getAnnualPay(r) * percentageIncrease) / 2080;
}
public String toString() {
return "Your rate : " + rate + " ";
}
}
public class SalariedWorker extends Worker implements Annual {
private double salary;
private double AnnualPayment;
private double percentageIncrease;
SalariedWorker() {
}
SalariedWorker(double s) {
salary = s;
}
public double getAnnualPay(double Annualpayment) {
return Annualpayment = salary * 12;
}
public void increasePayment(double r) {
increasePayS(r);
}
public double increasePayS(double r) {
return salary = (AnnualPayment + getAnnualPay(r) * percentageIncrease) / 12;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public double getAnnualPayment() {
return AnnualPayment;
}
public void setAnnualPayment(double AnnualPayment) {
this.AnnualPayment = AnnualPayment;
}
public double getpercentageIncrease() {
return percentageIncrease;
}
public void setpercentageIncrease(double percentageIncrease) {
this.percentageIncrease = percentageIncrease;
}
public String toString() {
return " ";
}
}
public class Test {
public static void main(String[] args) {
Scanner prompt = new Scanner(System.in);
ArrayList<Worker> Worker1 = new ArrayList<Worker>();
Worker1.add(new SalariedWorker());// is it alright to create a subclass object here?
Worker1.add(new SalariedWorker(1000.0));// index 1
Worker1.add(new HourlyWorker());// index 2
Worker1.add(new HourlyWorker(100.0));// index 3
System.out.println("Enter your monthly salary: ");
double salary = prompt.nextDouble();
Worker1.get(0).getSalary(salary);//gets me an error
System.out.println("Enter your hourly rate: ");
double HourlyRate = prompt.nextDouble();
System.out.println("Enter the Percentage Increase for a Salaried worker: ");
double PercentIncreaseS = prompt.nextDouble();
Worker1.get(0).getpercentageIncrease(PercentIncreaseS);//gets me an error
System.out.println("Your Increased payment is: ");
System.out.println("Enter the Percentage Increase for an Hourly worker: ");
double PercentIncreaseH = prompt.nextDouble();
}
}
You are getting the error because the Worker class does not have a getSalary() method.
You need to cast the objects in the list to the appropriate sub-class type.
For example:
SalariedWorker sw = (SalariedWorker) Worker1.get(0);
sw.getSalary(salary);
Problem with below code fragment is:
ArrayList<Worker> Worker1 = new ArrayList<Worker>();
Worker1.get(0).getSalary(salary);
get will return you the abstraction which doesn't have the getSalary(salary) method. All you have to do is to cast each with respective implementation class and the invoke the method on it.
Ex:
SalariedWorker sw = (SalariedWorker)Worker1.get(0);
So I'm supposed to design and implement an ADT that represents a credit card. It should include customer name, account number, due date, reward points, and account balance. There should be operations for a credit card charge, a cash advance, a payment, the addition of interest to the balance, and the display of the statistics of the bank account. However when I run my program,
I keep getting an error saying "Class "creditCard" does not have a main method."
import java.util.Scanner;
import javax.swing.*;
import java.awt.*;
import java.net.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.IOException;
public class creditCard {
private int customerName;
private int accountNumber;
private int dueDate;
private int rewardPoints;
private int accountBalance;
static Scanner input = new Scanner(System.in);
double creditLimit = 500;
int user = 0;
public int getCustomerName() {
return customerName;
}
public void setCustomerName(int customerName) {
this.customerName = customerName;
}
public int getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(int accountNumber) {
this.accountNumber = accountNumber;
}
public int getDueDate() {
return dueDate;
}
public void setDueDate(int dueDate) {
this.dueDate = dueDate;
}
public int getRewardPoints() {
return rewardPoints;
}
public void setRewardPoints(int rewardPoints) {
this.rewardPoints = rewardPoints;
}
public int getAccountBalance() {
return accountBalance;
}
public void setAccountBalance(int accountBalance) {
this.accountBalance = accountBalance;
}
public String charge(float amount) {
if (amount > creditLimit) {
System.out.println("You have exceeded your credit card limit and no charge can be made");
}
if (creditLimit - amount > 0) {
System.out.println("You have exceeded your credit card limit and no charge can be made");
}
creditLimit = creditLimit - amount;
System.out.println("A charge of" + amount + "has been made.");
String charge = "A charge of" + amount + "has been made.";
return charge;
}
public String advance(float amount) {
if (amount > creditLimit) {
System.out.println("You have exceeded your credit card limit and no charge can be made");
}
if (creditLimit - amount > 0) {
System.out.println("You have exceeded your credit card limit and no charge can be made");
}
creditLimit = creditLimit - amount;
System.out.println("You have withdrawn $ " + amount);
String advance = "You have withdrawn $ " + amount;
return advance;
}
public String payment(float amount) {
creditLimit = creditLimit + amount;
System.out.println("You have a credit limit of $ " + creditLimit);
String payment = "You have a credit limit of $ " + creditLimit;
return payment;
}
public String interest() {
creditLimit = (creditLimit * 0.02) + creditLimit;
String interest = "An interest of" + creditLimit * 0.02 + "has been added to your balance";
return interest;
}
public void statistics(String charge, String advance, String payment, String interest) {
System.out.println(charge);
System.out.println(advance);
System.out.println(payment);
System.out.println(interest);
}
public void showMenu() {
while (user!= 5) {
System.out.println("Choose Charge(1) \nAdvance(2) \nPayment(3) \nInterest(4) \ncStatistics(5)");
user = input.nextInt();
switch (user) {
case 1:
float amount;
System.out.println("Enter the amount: ");
amount = input.nextFloat();
String charge = charge(amount);
break;
case 2:
float withdrawalAmount;
System.out.println("Enter amount to withdraw: ");
withdrawalAmount = input.nextFloat();
String advance = advance(withdrawalAmount);
break;
case 3:
float paymentAmount;
System.out.println("Enter payment.");
paymentAmount = input.nextFloat();
String payment = payment(paymentAmount);
break;
case 4:
String interest = interest();
break;
//case 5:
//statistics(charge, advance, payment, interest);
//break;
}
}
}
public void main(String[] args) {
showMenu();
}
}
make the main method static.
public static void main(String[] args) {
showMenu();
}
or better create another entry point class and put your main there.
public class Runner {
public static void main(String[] args) {
CreditCard creditCard= new CreditCard();
creditCard.showMenu();
// Do something else
}
I have two objects derived from an Account class stored in an ArrayList. I am trying to call overridden methods with a basic for loop but I can't get it to work consistently.
import java.util.ArrayList;
import java.util.Scanner;
public class InheritanceTest
{
private static class Account
{
//Constructor
Account()
{
}
private void processDeposit()
{
double deposit = 0;
System.out.println("Please enter the deposit amount: ");
deposit = input.nextDouble();
balance += deposit;
}
private void processWithdrawal()
{
double withdrawal = 0;
System.out.println("Please enter the amount to be drawn from the account: ");
withdrawal = input.nextDouble();
balance -= withdrawal;
}
public String getAccountName() {
System.out.println("Creating " + "account, enter name: ");
accountName = input.nextLine();
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public int getAcctID() {
System.out.println("Your " + "account number is " + acctID);
return acctID;
}
public void setAcctID(int acctID) {
this.acctID = acctID;
acctID++;
}
}
//
private static class CheckingAccount extends Account
{
public String getAccountName() {
System.out.println("Creating checking account, enter name: ");
accountName = input.nextLine();
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
private void processWithdrawal()
{
double withdrawal = 0;
System.out.println("Please enter the amount to be drawn from the account: ");
withdrawal = input.nextDouble();
if (withdrawal > balance)
{
balance -= 10;
System.out.println("Overdraft fee has been charged");
} else
balance -= withdrawal;
}
}
//
private static class SavingsAccount extends Account
{
public String getAccountName() {
System.out.println("Creating savings account, enter name: ");
accountName = input.nextLine();
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
private void processWithdrawal()
{
double withdrawal = 0;
System.out.println("Please enter the amount to be drawn from the account: ");
withdrawal = input.nextDouble();
if(withdrawal > balance)
{
System.out.println("Insufficient funds");
} else
{
balance -= withdrawal;
}
}
}
//
public static void main(String[] args)
{
ArrayList<Account> Bank = new ArrayList<Account>();
CheckingAccount checking1 = new CheckingAccount();
Bank.add(checking1);
SavingsAccount savings = new SavingsAccount();
Bank.add(savings);
for(int i = 0; i<Bank.size(); i++)
{
Bank.get(i).getAccountName();
Bank.get(i).setAccountName(Bank.get(i).accountName);
Bank.get(i).getAcctID();
Bank.get(i).setAcctID(Bank.get(i).acctID);
}
for (int i =0; i<Bank.size(); i++)
{
System.out.println("Processing Account: " + Bank.get(i).acctID);
Bank.get(i).processDeposit();
System.out.println("Balance: " + Bank.get(i).balance);
Bank.get(i).processWithdrawal();
System.out.println("Balance: " + Bank.get(i).balance);
Bank.get(i).processWithdrawal();
Bank.get(i).displayAccount(Bank.get(i).acctID, Bank.get(i).accountName, Bank.get(i).balance);
}
}
}
The first loop calls the overridden getAccountName methods just fine, yet the second loop only seems to be calling the processWithdrawal method from the base class. Can anyone point me in the direction of finding out why this might be happening?
private void processWithdrawal()
make it public
public void processWithdrawal()
When you would like to override a method i.e. leverage the feature of Dynamic Polymorphism the method should be protected/public.
A private method is restricted only to that specific class in which it is declared which wouldnt make Overriding possible.
I have problem on how to print the polymorphic object in the array, where inheritance is applicable. I know how to store it in the single array, but when it comes to print the object, I am totally stuck.
Here is my main class:
public class AccountArray {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n, i = 0;
int numAcc;
double balance, rate;
Account[] bank = new Account[2];
do {
System.out.print("\n[1]Current || [2]Saving >> ");
n = in.nextInt();
System.out.println("------------");
if (n == 1) {
bank[i] = new Current();
System.out.println("#Current#");
System.out.println("------------");
System.out.print("Please enter account number: ");
numAcc = in.nextInt();
bank[i].setAccountNumber(numAcc);
System.out.print("Enter balance: ");
balance = in.nextDouble();
bank[i].setAccountBalance(balance);
i++;
} else if (n == 2) {
bank[i] = new Saving();
System.out.println("#Saving#");
System.out.println("------------");
System.out.print("Please enter account number: ");
numAcc = in.nextInt();
bank[i].setAccountNumber(numAcc);
System.out.print("Enter balance: ");
balance = in.nextDouble();
bank[i].setAccountBalance(balance);
System.out.print("Interest rate: ");
rate = in.nextDouble();
((Saving) bank[i]).setInterest(rate);
System.out.println("---------------------------------------");
i++;
}
} while (i < bank.length);
//Output
System.out.println("### Data Output ###");
for (int d = 0; d < bank.length; d++) {
System.out.println("--------------------");
System.out.println("Account Number: \t" + bank[d].getAccountNumber());
System.out.println("Balance : \t" + bank[d].getAccountBalance());
if (bank[d] == new Saving()) {
System.out.println("Interest rate : " + ((Saving) bank[d]).getInterest());
}
}
}
Here is my Account class with abstract class:
public abstract class Account {
private int numAcc;
private double balance;
public Account() {
}
public Account(int numAcc, double balance) {
this.numAcc = numAcc;
this.balance = balance;
}
public int getAccountNumber() {
return numAcc;
}
public void setAccountNumber(int numAcc) {
this.numAcc = numAcc;
}
public double getAccountBalance() {
return balance;
}
public void setAccountBalance(double balance) {
this.balance = balance;
}
public abstract void display();
}
Here is the Saving Class
public class Saving extends Account {
private double interest;
public Saving(int numAcc, double balance, double interest) {
super(numAcc, balance);
this.interest = interest;
}
public Saving() {
}
public void setInterest(double interest) {
this.interest = interest;
}
public double getInterest() {
return interest;
}
#Override
public void display() {
System.out.println("Saving Account Information");
System.out.println("account number: " + getAccountNumber());
System.out.println("balance: RM " + getAccountBalance());
System.out.println("interest: " + getInterest() + " %");
}
}
This is my current class:
public class Current extends Account {
public Current(int accNum, double balance) {
super(accNum, balance);
}
public Current() {
}
#Override
public void display() {
System.out.println("Current Account Information");
System.out.println("account number: " + getAccountNumber());
System.out.println("balance: RM " + getAccountBalance());
}
}
Other approach is to override toString() method of each Object.
bank[d] == new Saving() this is wrong and you try if(bank[d] instance of Saving)