Heres the full error
Exception in thread "main" java.lang.NullPointerException
at EmployeeManager.addEmployee(EmployeeManager.java:38)
at EmployeeDriver.main(EmployeeDriver.java:231)
here is where the errors are coming from
public class EmployeeManager
{
private Employee[] employees;
private final int employeeMax = 100;
private int currentEmployees;
public EmployeeManager()
{
Employee[] employees = new Employee[employeeMax];
currentEmployees = 0;
}
public void addEmployee(int eType, String fn, String ln, char m, char g, int empNum, boolean ft, double a)
{
double sales = 0.0, hoursWorked = 0.0;
switch (eType)
{
/*error*/ case 1: employees[currentEmployees] = new HourlyEmployee(fn, ln, m, g, empNum, ft, a, hoursWorked);
currentEmployees++;
break;
case 2: employees[currentEmployees] = new SalaryEmployee(fn, ln, m, g, empNum, ft, a);
currentEmployees++;
break;
case 3: employees[currentEmployees] = new CommissionEmployee(fn, ln, m, g, empNum, ft, a, sales);
currentEmployees++;
break;
}
}
///////////////////////////////////////////////////////////////////////////////////////////
//Add Employee
case 2:
String fn, ln;
char mi, g, f;
boolean ft = true;
do
{
System.out.println("\n1. Hourly");
System.out.println("2. Salary");
System.out.println("3. Commission");
System.out.print("Enter Choice: ");
subInput1 = in.nextInt();
if(subInput1 < 1 || subInput1 > 3)
{
System.out.println("Invalid Choice! Choose again.");
}
}while(subInput1 < 1 || subInput1 > 3);
System.out.print("Enter Last Name: ");
ln = in.next();
System.out.print("Enter First Name: ");
fn = in.next();
System.out.print("Enter Middle Initial: ");
mi = in.next().charAt(0);
System.out.print("Enter Gender: ");
g = in.next().charAt(0);
System.out.print("Enter Employee Number: ");
en = in.nextInt();
System.out.print("Full Time? (y/n): ");
f = in.next().charAt(0);
if(f == 'n' || f == 'N')
{
ft = false;
}
if(subInput1 == 1)
{
System.out.print("Enter wage: ");
}
else if(subInput1 == 2)
{
System.out.print("Enter salary: ");
}
else
{
System.out.print("Enter rate: ");
}
amount = in.nextDouble();
/*error*/ em.addEmployee(subInput1, fn, ln , mi, g, en, ft, amount);
em.removeRedundancies();
break;
Now as far as i am concerned i am making a new instantiation of HourlyEmployee which holds all of these values in the employees array. HourlyEmployee is a subclass of superclass Employee. Here's my code for those two.
public class HourlyEmployee extends Employee
{
private double wage;
private double hoursWorked;
public HourlyEmployee(String fn, String ln, char m, char g, int empNum, boolean ft, double w, double h)
{
super (fn, ln, m, g, empNum, ft);
wage = w;
hoursWorked = h;
hoursWorked = 0.0;
}
#Override
public String toString()
{
return this.getEmployeeNumber() + "\n" + lastName + ", " + firstName + middleInitial + "\n" + "Gender: "
+ this.getGender() + "\n" + "Status: " + fulltime + "\n" + "Wage: " + wage + "\n" + "Hours Worked: " + hoursWorked + "\n";
}
#Override
public double calculateWeeklyPay()
{
if (hoursWorked > 40)
{
wage = wage * 2;
}
return wage * hoursWorked;
}
#Override
public void annualRaise()
{
wage = (wage * .05) + wage;
}
#Override
public double holidayBonus()
{
return wage * 40;
}
#Override
public void resetWeek()
{
hoursWorked = 0.0;
}
public double plusHoursWorked(double amount, double h)
{
while (amount <= 0)
{
System.out.println("Invalid value entered, please try again");
}
return amount + h;
}
}
///////////////////////////////////////////////////////////////////////////////////////////
public abstract class Employee
{
protected String firstName;
protected String lastName;
protected char middleInitial;
protected boolean fulltime;
private char gender;
private int employeeNum;
public Employee (String fn, String ln, char m, char g, int empNum, boolean ft)
{
firstName = fn;
lastName = ln;
middleInitial = m;
gender = g;
employeeNum = empNum;
fulltime = ft;
}
public int getEmployeeNumber()
{
return employeeNum;
}
public void setEmployeeNumber(int empNum)
{
while (empNum <= 10000 && empNum >= 99999)
{
System.out.print ("Invalid input, please try again: ");
}
if (empNum >= 10000 && empNum <= 99999)
{
employeeNum = empNum;
}
}
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
public char checkGender(char g)
{
if (g != 'M' || g != 'F')
{
g = 'F';
}
return g;
}
public char getGender()
{
return gender;
}
#Override
public boolean equals(Object e2)
{
if (this.employeeNum == ((Employee)e2).employeeNum)
{
return true;
}
else
{
return false;
}
}
#Override
public String toString()
{
return employeeNum + "\n" + lastName + ", " + firstName + "\n" + "Gender:" + gender + "\n" + "Status:" + fulltime + "\n";
}
public abstract double calculateWeeklyPay();
public abstract void annualRaise();
public abstract double holidayBonus();
public abstract void resetWeek();
}
I honestly have no idea what I am doing wrong, if someone could point me in the right direction I would really appreciate it. Thank you!
Local declaration of
Employee[] employees = new Employee[employeeMax];
hides the instance variable, try with:
employees = new Employee[employeeMax];
otherwise the employees you are instantiating is a local variable which disappears after the call to the constructor.
In your situation you have
Employees[] e = NULL;
method()
{
Employees[] e = new Employees[N]; // this declares a different variable with same name
}
method2()
{
.. e[0] .. // exception: e was still NULL
}
Related
I'm working on a baking system program for a school project which includes the ff. features:
Creating a new account
Balance Inquiry
Deposit
Withdraw
Close account
So far here's the code I've written:
class BankAccountAndaya {
private String accountName, address, birthday, contactNumber;
Scanner sc = new Scanner(System.in);
//default constructor
public BankAccountAndaya() {
}
public BankAccountAndaya(String accountName, String address, String birthday, String contactNumber){
this.accountName = accountName;
this.address = address;
this.birthday = birthday;
this.contactNumber = contactNumber;
}
//accessor
public String getAccountName() {
return accountName;
}
public String getAddress() {
return address;
}
public String getBirthday() {
return birthday;
}
public String getContactNumber() {
return contactNumber;
}
//mutators
public void setAccountName(String name) {
this.accountName = name;
}
public void setAddress(String address) {
this.address = address;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public void setContactNumber(String contactNum) {
this.contactNumber = contactNum;
}
public void getClientDetails() {
System.out.print("Enter name: ");
setAccountName(sc.next());
System.out.print("Enter address: ");
setAddress(sc.next());
System.out.print("Enter birthday (MM/DD/YY): ");
setBirthday(sc.next());
System.out.print("Enter contact number: ");
setContactNumber(sc.next());
}
}
public class SavingsAccountAndaya extends BankAccountAndaya {
private int accountNo;
private double balance, interestRate;
Random rd = new Random();
Scanner sc = new Scanner(System.in);
// default constructor
SavingsAccountAndaya() {
}
// accessors
public int getAccountNo() {
return accountNo;
}
public double getBalance() {
return balance;
}
public double getInterestRate() {
return interestRate;
}
// mutators
public void setAccountNo(int acctNo) {
this.accountNo = acctNo;
}
public void setBalance(double bal) {
this.balance = bal;
}
public void setInterestRate(double intR) {
this.interestRate = intR;
}
public boolean validateAcctNumber(int search) {
for (int i = 0; i < 100; i++) {
int listVal = getAccountNo();
if (search == listVal) {
return true;
}
}
return false;
}
public void balanceInquiry() {
System.out.print("Enter account number: ");
int search = sc.nextInt();
boolean result = validateAcctNumber(search);
if (result) {
System.out.println("Client name: " + getAccountName());
System.out.println("Balance: " + getBalance());
} else {
System.out.println("Account number invalid!");
}
}
public void deposit() {
System.out.print("Enter account number: ");
int search = sc.nextInt();
boolean result = validateAcctNumber(search);
if (result) {
System.out.print("Enter amount to deposit: ");
double deposit = sc.nextDouble();
if (deposit >= 100) {
balance += deposit;
interestRate = 0.05 * balance;
balance += interestRate;
System.out.println("Amount deposit successful!");
System.out.println("Updated balance: " + balance);
} else {
System.out.println("Invalid deposit number!");
}
} else {
System.out.println("Invalid account number!");
}
}
public void withdraw() {
System.out.print("Enter account number: ");
int search = sc.nextInt();
boolean result = validateAcctNumber(search);
if (result) {
System.out.print("Enter amount to withdraw: ");
double withdraw = sc.nextDouble();
double mainBal = withdraw - balance;
if (withdraw >= 100 && withdraw < balance && mainBal >= 5000) {
balance -= withdraw;
System.out.println("Amount withdrawn successful!");
System.out.println("Updated balance: " + balance);
} else {
System.out.println("Invalid withrawal amount!");
}
} else {
System.out.println("Invalid account number!");
}
}
public void closeAccount() {
System.out.print("Enter account number: ");
int search = sc.nextInt();
boolean result = validateAcctNumber(search);
if (result) {
setAccountNo(0);
setBalance(0);
setAccountName("");
setAddress("");
setBirthday("");
setContactNumber("");
} else {
System.out.println("Invalid account number!");
}
}
}
public class ClientAndaya extends SavingsAccountAndaya {
/**
* #param args the command line arguments
*/
public static void displayMainMenu() {
System.out.println("JBank Main Menu");
System.out.println("[1] New Account");
System.out.println("[2] Balance Inquiry");
System.out.println("[3] Deposit");
System.out.println("[4] Withdraw");
System.out.println("[5] Client Profile");
System.out.println("[6] Close Account");
System.out.println("[7] Exit");
}
public static void main(String[] args) {
int i = 0;
SavingsAccountAndaya[] sa = new SavingsAccountAndaya[100];
Random rd = new Random();
Scanner sc = new Scanner(System.in);
int input;
do {
displayMainMenu();
System.out.print("Enter number: ");
input = sc.nextInt();
sa[i] = new SavingsAccountAndaya();
switch (input) {
case 1:
System.out.println("New Account: ");
sa[i].getClientDetails();
System.out.print("Enter amount to deposit: ");
double inDepo = sc.nextDouble();
if (inDepo < 5000) {
System.out.println("Invalid initial deposit amount!");
System.out.println("Amount must be greater than 5000 PHP");
System.out.print("Enter amount to deposit: ");
inDepo = sc.nextDouble();
}
sa[i].setBalance(inDepo);
// generate account number
int ranNo = rd.nextInt(9999);
sa[i].setAccountNo(ranNo);
System.out.println("Account number: " + sa[i].getAccountNo());
i++;
break;
case 2:
System.out.println("Balance Inquiry: ");
sa[i].balanceInquiry();
break;
case 3:
System.out.println("Deposit: ");
sa[i].deposit();
break;
case 4:
System.out.println("Withdraw: ");
sa[i].withdraw();
break;
case 5:
System.out.println("Client Profile: ");
System.out.println("Account number: " + sa[i].getAccountNo());
System.out.println("Accoutn Name: " + sa[i].getAccountName());
System.out.println("Address: " + sa[i].getAddress());
System.out.println("Birthday: " + sa[i].getBirthday());
System.out.println("Contact Number: " + sa[i].getContactNumber());
System.out.println("Balance: " + sa[i].getBalance());
break;
case 6:
System.out.println("Close Account: ");
sa[i].closeAccount();
break;
case 7:
break;
default:
System.out.println("Invalid chosen number!");
}
} while (input < 6 && input > 0);
}
}
I can't seem to access or search for an account I've created. Whenever I input the account number, it always results to invalid account number even though I've already created an account that has that account number. I think the problem lies with the validateAcctNumber method:
public boolean validateAcctNumber(int search) {
for (int i = 0; i < 100; i++) {
int listVal = getAccountNo();
if (search == listVal) {
return true;
}
}
return false;
}
It was also mentioned in the instructions to use exception to validate inputs.
How can I solve this problem? Thank you for your help.
I have a somewhat big code and I'm triying to print the slot number of an array from an object class that resulted to be the one with the highest weight.
On my main I have declared my array like this:
Car x[] = new car[2];
Now when triying to get which car has the highest weight I've made this validation inside a for loop
//.getweight obtains the weight of each car
if(x[i].getWeight() > max){
max = x[i].getWeight();
}
That code gives me the actual weight number of the heaviest car, but what I want to print is the actual car number. The comparing works but I can't find a way to just print the slot that corresponds to the heaviest car.
UPDATE with full code:
My object car:
public class Car
{
private String color;
private int weight;
private int state;
private int fuel;
private int Maxspeed ;
private int engine;
public Car(){
this.color = "White";
this.weight = 1000;
this.state = 0;
this.fuel =0;
this.Maxspeed = 0;
this.engine = 0;
}
public Car( String color, int weight,
int state, int fuel, int Maxspeed
){
this.color = color;
this.weight = weight;
this.state = state;
this.fuel = fuel;
this.Maxspeed = Maxspeed;
}
public String getColor(){
return this.color;
}
public int getweight(){
return this.weight;
}
public int getstate(){
return this.state;
}
public int getfuel(){
return this.fuel;
}
public int getMaxspeed(){
return this.Maxspeed;
}
public int getengine(){
return this.engine;
}
public void setColor( String color ){
this.color = color;
}
public void setweight( int weight ){
this.weight = weight;
}
public void setstate( int state ){
this.state = state;
}
public void setfuel( int fuel ){
this.fuel = fuel;
}
public void setMaxspeed( int Maxspeed ){
this.Maxspeed = Maxspeed;
}
public void setengine(int engine){
this.engine = engine;
}
public void showdata(){
System.out.println( "\nCar's color is: " + this.getColor() );
System.out.println( "Car's weight is: " + this.getweight() );
System.out.println( "State: " + this.getstate() );
System.out.println( "Fuel: " + this.getfuel());
System.out.println( "Max speed: " + this.getMaxspeed());
}
public void accelerate( int speed ){
if( this.getstate() == 0 ||
this.getstate() == 3 ||
this.getstate() == 4 ||
this.getMaxspeed() < speed )
{
System.out.println("\nCar cannot accelerate...");
}
else{
System.out.println("\nCar is accelerating...");
this.setfuel(this.getfuel()-2);
this.setstate(2);
if( this.getfuel() <= 0 ){
this.setstate(4);
}
}
}
public void crash(){
this.setstate(3);
System.out.println("\nCrash!!!");
}
public void stop(){
this.setstate(1);
System.out.println("\nCar has stopped.");
}
public void addfuel(int fuel){
if(this.getstate() == 0 || this.getstate() == 4){
this.setfuel(this.getfuel()+ fuel);
}
else{
System.out.println("You can't add fuel.");
}
}
public void repair(){
if(this.getstate() == 3){
this.setstate(1);
System.out.println("The car has been repaired");
}
else{
System.out.println("The car is not broken");
}
}
}
My Main:
import java.util.Scanner;
public class aaa{
public static void main (String args []){
Car x[] = new Car[2];
int keep=1;
int counter = 0;
int counter_stopped = 0;
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
int maxIndex = 0;
int maxweight = 0;
int index_engine = 0;
int min_engine = 0;
Scanner input = new Scanner(System.in);
for(int i = 0; i < x.length; i++){
String color;
int weight;
int fuel;
int Maxspeed;
int engine;
x[i] = new Car();
System.out.print("\nEnter car color " + (i + 1) + ": ");
color = input.next();
System.out.print("Enter car weight " + (i + 1) + ": ");
weight = input.nextInt();
System.out.print("Enter car fuel " + (i + 1) + ": ");
fuel = input.nextInt();
System.out.print("Enter car max speed " + (i + 1) + ": ");
Maxspeed = input.nextInt();
System.out.print("Enter car engine weight " + (i + 1) + ": ");
engine = input.nextInt();
x[i].setColor(color);
x[i].setweight(weight);
x[i].getstate();
x[i].setfuel(fuel);
x[i].setMaxspeed(Maxspeed);
x[i].setengine(engine);
}
for(int i = 0; i < x.length; i++){
int state;
System.out.print("\nEnter car state " + (i + 1) + ": ");
state = input.nextInt();
x[i].setstate(state);
while(state > 4 || state < 0){
System.out.print("state not valid.\nTry again: ");
state = input.nextInt();
x[i].setstate(state);
}
do {
keep = menu();
switch( keep ){
case 1:
accelerate(x[i]);
break;
case 2:
stop(x[i]);
break;
case 3:
crash(x[i]);
break;
case 4:
addfuel(x[i]);
break;
case 5:
repair(x[i]);
break;
case 6:
x[i].showdata();
}
} while(keep != 7);
if(x[i].getstate() == 4 || x[i].getfuel() <= 0){
counter += 1;
}
if(x[i].getstate() == 1){
counter_stopped += 1;
}
int weight = x[i].getweight();
if(weight > max){
maxweight = weight;
maxIndex = i;
}
int weightengine = x[i].getengine();
if(weightengine < min){
min_engine = weightengine;
index_engine = i;
}
}
System.out.println("\nSUMMARY");
System.out.println("Amount of cars with no fuel: " + counter);
System.out.println("Amount of stopped cars: " + counter_stopped);
System.out.println("Heaviest car: " + maxIndex);
System.out.println("Car with the smallest engine: " + index_engine);
System.out.println("=============================================");
}
public static int menu(){
int option = 0;
Scanner s = new Scanner(System.in);
System.out.println("\n1. Accelerate Car ");
System.out.println("2. Stop Car ");
System.out.println("3. Crash Car ");
System.out.println("4. Add fuel ");
System.out.println("5. Repair ");
System.out.println("6. Show data ");
System.out.println("7. Exit ");
System.out.println("=============================================");
System.out.print("Choose an option : ");
option = s.nextInt();
System.out.println("=============================================");
return option;
}
public static void accelerate(Car myCar){
Scanner input = new Scanner(System.in);
int s;
System.out.print("Enter speed: ");
s = input.nextInt();
myCar.accelerate(s);
//myCar.showdata();
}
public static void stop(Car myCar){
myCar.stop();
}
public static void crash(Car myCar){
myCar.crash();
}
public static void addfuel(Car myCar){
int fuel;
Scanner input = new Scanner(System.in);
System.out.print("Amount to add: ");
fuel = input.nextInt();
myCar.addfuel(fuel);
}
public static void repair(Car myCar){
myCar.repair();
}
}
Now, when I compile and test which engine or car is smaller or heaviest I get the number 1 as result.
The array index would be i
The actual car would be x[i]
You need to hold on to a reference to the index to the heaviest car. In this example I am using maxIndex.
float maxWeight = 0;
int maxIndex = 0;
for (int i = 0; i < x.length; i++) {
float weight = x[i].getWeight();
if (weight > max) {
maxWeight = weight;
maxIndex = i;
}
}
System.out.println("Slot of heaviest car: " + maxIndex);
I am learning the basics at University and would like some help with the following error from Eclipse : "The method getCost() is undefined for the type ShopCLI" &
"Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method getCost() is undefined for the type ShopCLI
at components.ShopCLI.main(ShopCLI.java:39)
Here is my code
public class ShopCLI {
public static void main(String[] args) {
ArrayList<Order> ord = new ArrayList<>();
System.out.println("Welcome to Sandwich Shop CLI V1!");
System.out.println("Please Choose and Option by Typing the Appropriate Number from the List");
System.out.println("1.New Order");
Scanner sc = new Scanner(System.in);
int choice = sc.nextInt();
System.out.println("Please Choose an Outer From the List: ");
System.out.println("Press 1 to Continue or 2 to Exit");
int Sandwich = sc.nextInt();
System.out.println("Outer Options are Bun, Bread or Brioche");
String inputOuter = sc.next();
System.out.println("Inner Options are Ham, Cheese or Cucumber");
String inputInner = sc.next();
System.out.println("Sauce Options are Mayo, Butter or Marmite");
String inputSauce = sc.next();
if (Sandwich == 1){
ord.add(new Order(1, inputOuter, inputInner, inputSauce, 0));
System.out.println("You Made a " + inputInner + " with " + inputSauce + " Sandwich on " + inputOuter);
System.out.println("This Will Cost " + getCost());
}
else if (Sandwich == 2){
System.out.println("Exited.");
}
}
}
public class Sandwich {
//Fields
ArrayList<Sandwich> sandwich = new ArrayList<>();
String outer;
String inner;
String sauce;
//Constructor
public Sandwich(String outer, String inner, String sauce){
this.outer = outer;
this.inner = inner;
this.sauce = sauce;
}
//Methods
public String getOuter(){
return outer;
}
public String getInner(){
return inner;
}
public String getSauce(){
return sauce;
}
public void setOuter(String repOuter){
outer = repOuter;
}
public void setInner(String repInner){
inner = repInner;
}
public void setSauce(String repSauce){
sauce = repSauce;
}
public void createSandwich(String outer, String inner, String sauce){
sandwich.add(new Sandwich(outer, inner, sauce));
}
public void setSandwich(String repOuter, String repInner, String repSauce){
outer = repOuter;
inner = repInner;
sauce = repSauce;
}
public void resetOrder(){
sandwich.removeAll(sandwich);
}
}
public class Order extends Sandwich {
//Fields
int OrderId;
double Cost;
//Constructor
public Order(int OrderId, String outer, String inner, String sauce, int Cost) {
super(outer, inner, sauce);
this.OrderId = OrderId;
this.Cost = Cost;
}
//Methods
public int getOrderId(){
return this.OrderId;
}
public double getCost(){
return this.Cost;
}
public void setOrderId(int repOrderID){
this.OrderId = repOrderID;
}
public void overrideCost(int Cost){
this.Cost = Cost;
}
public void setOrder(int repOrderId, String repOuter, String repInner, String repSauce){
this.OrderId = repOrderId;
this.outer = repOuter;
this.inner = repInner;
this.sauce = repSauce;
double calcCost;
double outerCost = 0;
double innerCost = 0;
double sauceCost = 0;
//Outer Cost
if(repOuter == "Bun")
{
outerCost = 0.5;
}
else if(repOuter == "Bread")
{
outerCost = 0.25;
}
else if(repOuter == "Brioche")
{
outerCost = 0.75;
}
else
{
System.out.println("Invalid Bread Type");
}
//Inner cost
if(repInner == "Ham")
{
innerCost = 0.5;
}
else if(repInner == "Cheese")
{
innerCost = 0.25;
}
else if(repInner == "Cucumber")
{
innerCost = 0.75;
}
else
{
System.out.println("Invalid Filling Type");
}
//Sauce Cost
if(repSauce == "Mayo")
{
sauceCost = 0.5;
}
else if(repSauce == "Butter")
{
sauceCost = 0.25;
}
else if(repSauce == "Marmite")
{
sauceCost = 0.75;
}
else
{
System.out.println("Invalid Sauce Type");
}
calcCost = outerCost + innerCost + sauceCost;
this.Cost = calcCost;
}
}
getCost method is defined in order class and not in ShopCLI class. So your code:
ord.add(new Order(1, inputOuter, inputInner, inputSauce, 0));
System.out.println("You Made a " + inputInner + " with " + inputSauce + " Sandwich on " + inputOuter);
System.out.println("This Will Cost " + getCost());
Should be changed to
Order order = new Order(1, inputOuter, inputInner, inputSauce, 0);
ord.add(order);
System.out.println("You Made a " + inputInner + " with " + inputSauce + " Sandwich on " + inputOuter);
System.out.println("This Will Cost " + order.getCost());
^^^^^
you must get the object from the arraylist, then do acces the method:
//get obj,then void
System.out.println("This Will Cost " + ord.get(choise).getCost());
this will return 0, since you set the cost 0 in the constructor:
ord.add(new Order(1, inputOuter, inputInner, inputSauce, 0));
also, name your integer "Sandwich" to "sandwich" without the capital letter. otherwise, it looks like you mean the class "Sandwich"
In this line:
System.out.println("This Will Cost " + getCost());
...you don't specify what you want to call getCost() on, so it calls it on ShopCLI because that's where the call is happening. But ShopCLI doesn't have a getCost() method. You need to call it on your order:
System.out.println("This Will Cost " + ord.get(0).getCost());
This works, but when you create your Order object by calling the constructor, you're not calculating the cost, but rather setting whatever is passed in. Update your constructor to this:
//Constructor
public Order(int OrderId, String outer, String inner, String sauce) {
super(outer, inner, sauce);
this.OrderId = OrderId;
double calcCost;
double outerCost = 0;
double innerCost = 0;
double sauceCost = 0;
//Outer Cost
if(outer == "Bun")
{
outerCost = 0.5;
}
else if(outer == "Bread")
{
outerCost = 0.25;
}
else if(outer == "Brioche")
{
outerCost = 0.75;
}
else
{
System.out.println("Invalid Bread Type");
}
//Inner cost
if(inner == "Ham")
{
innerCost = 0.5;
}
else if(inner == "Cheese")
{
innerCost = 0.25;
}
else if(inner == "Cucumber")
{
innerCost = 0.75;
}
else
{
System.out.println("Invalid Filling Type");
}
//Sauce Cost
if(sauce == "Mayo")
{
sauceCost = 0.5;
}
else if(sauce == "Butter")
{
sauceCost = 0.25;
}
else if(sauce == "Marmite")
{
sauceCost = 0.75;
}
else
{
System.out.println("Invalid Sauce Type");
}
calcCost = outerCost + innerCost + sauceCost;
this.Cost = calcCost;
}
Now your constructor works, but you will have to remove an argument where you're calling it, so change your ord.add line to this:
ord.add(new Order(1, inputOuter, inputInner, inputSauce));
That should, if I'm not mistaken work. However, you might want to consider making a private helper method called calculateCost, so that you're not duplicating code between your constructor and your setOrder methods.
Create an Order
Order order = new Order(1, inputOuter, inputInner, inputSauce, 0);
ord.add(order) // Add the order to your list.
The cost for an order is set by the method setOrder(int repOrderId, String repOuter, String repInner, String repSauce)
change this method to the following.
public void setOrder() {
double calcCost;
double outerCost = 0;
double innerCost = 0;
double sauceCost = 0;
// Outer Cost
if (outer.equalsIgnoreCase("Bun")) {
outerCost = 0.5;
} else if (outer.equalsIgnoreCase("Bread")) {
outerCost = 0.25;
} else if (outer.equalsIgnoreCase("Brioche")) {
outerCost = 0.75;
} else {
System.out.println("Invalid Bread Type");
}
// Inner cost
if (inner.equalsIgnoreCase("Ham")) {
innerCost = 0.5;
} else if (inner.equalsIgnoreCase("Cheese")) {
innerCost = 0.25;
} else if (inner.equalsIgnoreCase("Cucumber")) {
innerCost = 0.75;
} else {
System.out.println("Invalid Filling Type");
}
// Sauce Cost
if (sauce.equalsIgnoreCase("Mayo")) {
sauceCost = 0.5;
} else if (sauce.equalsIgnoreCase("Butter")) {
sauceCost = 0.25;
} else if (sauce.equalsIgnoreCase("Marmite")) {
sauceCost = 0.75;
} else {
System.out.println("Invalid Sauce Type");
}
calcCost = outerCost + innerCost + sauceCost;
this.Cost = calcCost;
}
Now you can get the cost by calling the getCost() on the order as follows.
To calculate the order cost, call
order.setOrder();
To get the order cost, call
order.getCost();
NOTE: Don't use == to compare string. Always use equals() or equalsIgnoreCase().
i have modified your code for class ShopCLI
package tester;
import java.util.ArrayList;
import java.util.Scanner;
public class ShopCLI {
public static void main(String[] args) {
ArrayList<Order> ord = new ArrayList<>();
int orderNumber =1;
System.out.println("Welcome to Sandwich Shop CLI V1!");
System.out.println("start order");
Scanner sc = new Scanner(System.in);
while(true){
System.out.println("Press 1 for new order or 2 to Exit");
int choice = sc.nextInt();
if (choice == 1){
System.out.println("Enter outer Options:Outer Options are Bun, Bread or Brioche");
String inputOuter = sc.next();
System.out.println("Enter inner Options:Inner Options are Ham, Cheese or Cucumber");
String inputInner = sc.next();
System.out.println("Enter sauce Options:Sauce Options are Mayo, Butter or Marmite");
String inputSauce = sc.next();
Order order1 = new Order(orderNumber, inputOuter, inputInner, inputSauce, 0);
order1.setOrder(inputOuter, inputInner, inputSauce);
System.out.println("You Made a " + inputInner + " with " + inputSauce + " Sandwich on " + inputOuter);
System.out.println("This Will Cost " + order1.getCost());
ord.add(order1);
}
else if (choice == 2){
System.out.println("Exited.");
System.exit(1);
}
}
}
}
and format of setOrder method is modified too
public void setOrder(String repOuter, String repInner, String repSauce)
This is my code for STUDENT RECORD SYSTEM. I think it is on its 80% of completion. The problem here is that when i have many students and i update a specific student(subj & grade) the updated element is not being saved on that specific student. And when I display all of the results the updated values are given to other student. Please help me out with this issue. And btw this code has 2 classes Student and StudentGrade. I hope you'll help me fix this. Thanks in advance. :) and Advance Happy New Year!
public class Student
{
private String IDNumber;
private String firstName;
private String middleName;
private String lastName;
private String degree;
private int yearLevel;
public Student()
{
String IDNum;
String fName;
String mName;
String lName;
String deg;
int level;
}
public Student(String IDNum, String fName, String mName, String lName, String deg,int level )
{
this.IDNumber=IDNum;
this.firstName=fName;
this.middleName=mName;
this.lastName=lName;
this.degree=deg;
this.yearLevel=level;
}
public void setIdNumber(String IDNumber)
{
this.IDNumber = IDNumber;
}
public String getIdNumber()
{
return IDNumber;
}
public void setFirstName(String firstName)
{
this.firstName=firstName;
}
public String getFirstName()
{
return firstName;
}
public void setMiddleName(String middleName)
{
this.middleName=middleName;
}
public String getMiddleName()
{
return middleName;
}
public void setLastName(String lastName)
{
this.lastName=lastName;
}
public String getLastName()
{
return lastName;
}
public void setDegree(String degree)
{
this.degree=degree;
}
public String getDegree()
{
return degree;
}
public void setYearLevel(int yearLevel)
{
this.yearLevel=yearLevel;
}
public int getYearLevel()
{
return yearLevel;
}
}
public class StudentGrade
{
private String IDNumber;
private String subject;
private double grade;
private double average;
public StudentGrade()
{
String IDNum;
String sub;
double grad;
double ave;
}
public StudentGrade(String IDNum,String sub,double grad,double ave)
{
this.IDNumber=IDNum;
this.subject=sub;
this.grade=grad;
this.average=ave;
}
public void setSubject(String subject)
{
this.subject=subject;
}
public String getSubject()
{
return subject;
}
public void setGrade(double grade)
{
this.grade=grade;
}
public double getGrade()
{
return grade;
}
public String getIDNumber()
{
return IDNumber;
}
}
public class StudentGrade
{
private String IDNumber;
private String subject;
private double grade;
private double average;
public StudentGrade()
{
String IDNum;
String sub;
double grad;
double ave;
}
public StudentGrade(String IDNum,String sub,double grad,double ave)
{
this.IDNumber=IDNum;
this.subject=sub;
this.grade=grad;
this.average=ave;
}
public void setSubject(String subject)
{
this.subject=subject;
}
public String getSubject()
{
return subject;
}
public void setGrade(double grade)
{
this.grade=grade;
}
public double getGrade()
{
return grade;
}
public String getIDNumber()
{
return IDNumber;
}
}
import java.util.ArrayList;
import java.util.Scanner;
public class test2 {
static ArrayList<Student> studentList = new ArrayList<Student>();
static ArrayList<StudentGrade> studentLists = new ArrayList<StudentGrade>();
public static void main(String[] args)
{
menu();
}
public static void menu()
{
Scanner in = new Scanner(System.in);
int choice = 0;
System.out.print("*********STUDENT RECORD SYSTEM*********\n\n");
System.out.println("\t MENU ");
System.out.println("[1]ADD STUDENT");
System.out.println("[2]DISPLAY ALL");
System.out.println("[3]DISPLAY SPECIFIC");
System.out.println("[4]UPDATE");
System.out.println("[5]AVERAGE");
System.out.println("[6]EXIT");
System.out.println("?");
choice = in.nextInt();
if (choice == 1)
{
add();
}
else if (choice == 2)
{
displayAll();
}
else if (choice == 3)
{
displaySpecific();
}
else if (choice == 4)
{
update();
}
else if (choice == 5)
{
average();
}
else if( choice == 6)
{
System.exit(0);
}
else
menu();
}
public static void add()
{
Scanner in = new Scanner(System.in);
char ans;
String temp;
int total;
do {
System.out.println("NUMBER OF STUDENTS YOU WANT TO INPUT: ");
total = in.nextInt();
Student[] student = new Student[total];
for (int index = 0; index < student.length; index++) {
student[index] = new Student();
System.out.print("**********STUDENT INFORMATION**********\n\n");
System.out.println("PRESS ENTER");
in.nextLine();
System.out.print("ID NUMBER: ");
student[index].setIdNumber(in.nextLine());
System.out.print("FIRST NAME: ");
student[index].setFirstName(in.nextLine());
System.out.print("MIDDLE NAME: ");
student[index].setMiddleName(in.nextLine());
System.out.print("LAST NAME: ");
student[index].setLastName(in.nextLine());
System.out.print("DEGREE: ");
student[index].setDegree(in.nextLine());
System.out.print("YEAR LEVEL: ");
student[index].setYearLevel(in.nextInt());
studentList.add(student[index]);
}
System.out.print("Would you like to enter in a new student (y/n)? ");
String answer = in.next();
ans = answer.charAt(0);
} while (ans == 'y');
/* // SEARCH and DISPLAY SPECIFIC
String id = new String();
in.nextLine();
System.out.print("Enter ID NUMBER: ");
id = in.nextLine();
for (int j = 0; j < studentList.size(); j++) {
if (id.equals(studentList.get(j).getIdNumber())) {
System.out.printf("STUDENT SEARCHED");
System.out.print("\nID NUMBER: "
+ studentList.get(j).getIdNumber());
System.out.print("\nFULL NAME: "
+ studentList.get(j).getFirstName() + " "
+ studentList.get(j).getMiddleName() + " "
+ studentList.get(j).getLastName());
System.out.print("\nDEGREE and YEAR: "
+ studentList.get(j).getDegree() + "-"
+ studentList.get(j).getYearLevel() + "\n\n");
System.out.println();
}
}
// DISPLAY ALL
for (int i = 0; i < studentList.size(); i++) {
System.out.printf("STUDENT[%d]", i + 1);
System.out
.print("\nID NUMBER: " + studentList.get(i).getIdNumber());
System.out.print("\nFULL NAME: "
+ studentList.get(i).getFirstName() + " "
+ studentList.get(i).getMiddleName() + " "
+ studentList.get(i).getLastName());
System.out.print("\nDEGREE and YEAR: "
+ studentList.get(i).getDegree() + "-"
+ studentList.get(i).getYearLevel());
System.out.println();
} */
menu();
}
public static void displayAll() {
Scanner in = new Scanner(System.in);
if(studentList.size() == 0)
{
System.out.print("EMPTY lageeeee!!! \nPLEASE INPUT FIRST\n\n");
in.nextLine();
}
else
{
if(studentLists.size() == 0){
System.out.print("************STUDENT RECORD*************");
for (int i = 0; i < studentList.size(); i++) {
System.out.printf("\nSTUDENT[%d]", i + 1);
System.out
.print("\nID NUMBER: " + studentList.get(i).getIdNumber());
System.out.print("\nFULL NAME: "
+ studentList.get(i).getFirstName() + " "
+ studentList.get(i).getMiddleName() + " "
+ studentList.get(i).getLastName());
System.out.print("\nDEGREE and YEAR: "
+ studentList.get(i).getDegree() + "-"
+ studentList.get(i).getYearLevel()/* +"\nGrade: "
+ studentLists.get(i).getGrade() */+"\n\n");
}
in.nextLine();
}
else{
System.out.print("************STUDENT RECORD*************");
for (int i = 0; i < studentList.size(); i++)
{
System.out.printf("\nSTUDENT[%d]", i + 1);
System.out
.print("\nID NUMBER: " + studentList.get(i).getIdNumber());
System.out.print("\nFULL NAME: "
+ studentList.get(i).getFirstName() + " "
+ studentList.get(i).getMiddleName() + " "
+ studentList.get(i).getLastName());
System.out.print("\nDEGREE and YEAR: "
+ studentList.get(i).getDegree() + "-"
+ studentList.get(i).getYearLevel()+"\n\n");
}
for(int xxx = 0 ; xxx < studentLists.size(); xxx++ )
{
System.out.printf("\nSUBJECT: "
+ studentLists.get(xxx).getSubject()+" Grade: "
+ studentLists.get(xxx).getGrade());
}
in.nextLine();
}
}
menu();
}
public static void displaySpecific() {
Scanner in = new Scanner(System.in);
if(studentList.size() == 0)
{
System.out.print("EMPTY oe!!! KALAGOT!\nPLEASE INPUT FIRST\n");
in.nextLine();
}
else
{
String id = new String();
/* in.nextLine(); */
System.out.print("Enter ID NUMBER: ");
id = in.nextLine();
if(studentLists.size()==0)
{
for (int j = 0; j < studentList.size(); j++)
{
if (id.equals(studentList.get(j).getIdNumber()))
{
System.out.printf("\n*************STUDENT SEARCHED*************");
System.out.print("\nID NUMBER: "
+ studentList.get(j).getIdNumber());
System.out.print("\nFULL NAME: "
+ studentList.get(j).getFirstName() + " "
+ studentList.get(j).getMiddleName() + " "
+ studentList.get(j).getLastName());
System.out.print("\nDEGREE and YEAR: "
+ studentList.get(j).getDegree() + "-"
+ studentList.get(j).getYearLevel() + /* "\nGrade: "
+ studentLists.get(j).getGrade()+ */"\n\n");
System.out.println();
in.nextLine();
}
/* else
{
System.out.print("STUDENT DOES NOT EXIST IN THIS WORLD!");
in.nextLine();
} */
}
}
else
{
for (int j = 0; j < studentList.size(); j++)
{
if (id.equals(studentList.get(j).getIdNumber()))
{
System.out.printf("\n*************STUDENT SEARCHED*************");
System.out.print("\nID NUMBER: "
+ studentList.get(j).getIdNumber());
System.out.print("\nFULL NAME: "
+ studentList.get(j).getFirstName() + " "
+ studentList.get(j).getMiddleName() + " "
+ studentList.get(j).getLastName());
System.out.print("\nDEGREE and YEAR: "
+ studentList.get(j).getDegree() + "-"
+ studentList.get(j).getYearLevel() +"\n\n");
System.out.println();
}
}
for(int xxx = 0 ; xxx < studentLists.size(); xxx++ )
{
System.out.printf("\nSUBJECT: "
+ studentLists.get(xxx).getSubject()+" Grade: "
+ studentLists.get(xxx).getGrade());
}
in.nextLine();
}
}
menu();
}
public static void update()
{
Scanner in = new Scanner(System.in);
String idnum = new String();
char answer;
in.nextLine();
System.out.print("Enter ID NUMBER: ");
idnum = in.nextLine();
int total;
for(int x=0;x<studentList.size();x++)
{
if(idnum.equals(studentList.get(x).getIdNumber()))
{
System.out.println("NUMBER OF SUJECTS YOU WANT TO INPUT: ");
total = in.nextInt();
do
{
StudentGrade[] update = new StudentGrade[total];
for(int y = 0;y<update.length;y++)
{
update[y] = new StudentGrade();
in.nextLine();
System.out.print("ENTER SUBJECT: ");
update[y].setSubject(in.nextLine());
System.out.print("ENTER GRADE: ");
update[y].setGrade(in.nextDouble());
studentLists.add(update[y]);
}
System.out.print("Enter another subject and grade? [y/n]");
String ans = in.next();
answer = ans.charAt(0);
}while(answer == 'y');
}
menu();
}
}
public static void average()
{
Scanner in = new Scanner(System.in);
double sum=0;
double average=0;
String ID = new String();
System.out.print("ENTER ID NUMBER: ");
ID = in.nextLine();
for(int xx=0;xx<studentList.size();xx++)
{
if(ID.equals(studentList.get(xx).getIdNumber()))
{
for(int ind=0;ind<studentLists.size();ind++)
{
sum += studentLists.get(ind).getGrade();
average=sum/studentLists.size();
}
System.out.print("ID NUMBER:"+studentList.get(xx).getIdNumber()+"\nNAME: "
+studentList.get(xx).getFirstName()+" "
+studentList.get(xx).getMiddleName()+" "
+studentList.get(xx).getLastName());
System.out.print("\nAVERAGE: "+average+"\n");
in.nextLine();
}
}
menu();
}
}
First of all I would change studentList to Map to be able to get the student by id directly and not to search for the matching student every time.
The access to the collections of all students is then like this:
for(Map.Entry<String, Student> entry : studentList.entrySet()){
String id = entry.getKey();
Student student = entry.getValue();
// ...
}
A a second step you should check your update method. I see, that you a searching for the student, but you don't updating this object. You are adding a new one at the end of the loop with studentList.add().
You have store the matching Student into the local variable and just modify this without modifying the collection of students.
You have two reader statements in update function
public static void update()
{
Scanner in = new Scanner(System.in);
String idnum = new String();
char answer;
Scanner in = new Scanner(System.in);
String idnum = new String();
char answer;
in.nextLine();//1
System.out.print("Enter ID NUMBER: ");
idnum = in.nextLine();//2
I think there should be only one as your just reading the id number and as #Vlad said your adding a new element to the array list rather than modifying the existing data .
also for your code you can use
arrayList.set(index i,String replaceElement);// this will help you replace the value at a particular index
it is better to use HashMap instead of array list so when you put an existing element into
a map the value is overwritten.
static Map <String,Student> studentList = new HashMap<String,Student>();
static Map<String, List<StudentGrade>> studentLists = new HashMap<String, List<StudentGrade>>();
Here the key will be the student idNumber
I have programed a Worker and MachineWorker class. It complies fine. but when i run it, after three consecutive statements the program stops. I cannot find the problem, and I dont know how and when to use 'instanceof'.
I am writing the question below and with all the classes...
Question:- (i)Declare an array that can store the references of up to 5 Worker or MachineWorker objects.
a)Allow user to enter the type of object and the data for that type of object(3 values for Worker and 4 values for MachineWorker).
b)Construct the appropriate object storing the reference in the common array.
ii)Now allow the users to enter the weekly data repeatedly. If it is Worker object user must enter ID and hours-worked. If it is a MachineWorker object user must enter ID,hoursWorked and pieces. Once these values read search through the array to locate the object with the given ID before calling the addWeekly().The number of arguments either(1 or 2) to be passed to addWeekly depends on the type of objects being referred. To determine the type of object being referred(Worker or MachineWorker)you may use the instanceof operator.
Please see my codes below:-
//Worker.java
public class Worker {
public final double bonus=100;
protected String name, workerID;
protected double hourlyRate, totalHoursWorked,tax,grossSalary,netSalary;
public Worker(){
}
public Worker(String name, String workerID, double hourlyRate){
this.name = name;
this.workerID = workerID;
this.hourlyRate = hourlyRate;
}
public void addWeekly(double hoursWorked){
this.totalHoursWorked = this.totalHoursWorked + hoursWorked;
}
public double gross(){
grossSalary = (totalHoursWorked*hourlyRate);
if(totalHoursWorked>=150){
grossSalary = grossSalary +100;
}
return grossSalary;
}
public double netAndTax(){
netSalary = grossSalary;
if(grossSalary>500){
tax = (grossSalary - 500) *0.3;
netSalary = (grossSalary - tax);
}
return netSalary;
}
public String getName(){
return this.name;
}
public String getWorkerID(){
return this.workerID;
}
public double getHourlyRate(){
return this.hourlyRate;
}
public double getTotalHours(){
return totalHoursWorked;
}
public double getGrossSalary(){
return grossSalary;
}
public void addToGross(double amt){
grossSalary = grossSalary + amt;
}
public void displaySalary(){
System.out.print("Name: " +getName() + "\nID :" + getWorkerID()
+ "\nHourly Rate: " + getHourlyRate()+ "\nTotalHours Worked" + getTotalHours() +
"\nGross pay" + getGrossSalary() + "\nTax: " + netAndTax() +
"\nNet Pay: " + netAndTax());
}
}
//MachineWorker.java
public class MachineWorker extends Worker{
private double targetAmount;
private double totalPieces, productivityBonus;
public MachineWorker(String workerName, String workerID, double hourlyRate, double targetAmount)
{
super(workerName, workerID, hourlyRate);
//this.productivityBonus = productivityBonus;
this.targetAmount = targetAmount;
}
public void addWeekly(double hoursWorked, double weeklyAmount)
{
totalHoursWorked = hoursWorked + totalHoursWorked;
totalPieces = weeklyAmount + totalPieces;
}
public double productivityBonus()
{
productivityBonus = 100 + (totalPieces - targetAmount);
return productivityBonus;
}
public double gross()
{
grossSalary = (totalHoursWorked * hourlyRate) + productivityBonus;
if(totalHoursWorked >= 150)
{
grossSalary = grossSalary + bonus;
}
return grossSalary;
}
public void addToGross(double amt)
{
amt = productivityBonus;
grossSalary = grossSalary + amt;
}
public void displaySalary()
{
System.out.println("Name " + super.name + "\nID " +
super.workerID + "\nHourly rate " + super.hourlyRate + "\nTotal Hours Worked " +
super.totalHoursWorked + "\nGross Pay $" + super.grossSalary + "\nTax $" + super.tax + "\nNetpay $" + super.netSalary);
System.out.println("Productivity Bonus " + productivityBonus);
}
}
//Polymorphism PolyWorker.java
import java.util.*;
public class PolyWorkers
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
Worker[] a = new Worker[5];
MachineWorker[] b = new MachineWorker[5];
char option = '0';
String choice;
boolean nChar = false;
for (int i = 0; i < 5; i++){
System.out.print("\tType of object " + (i+1) + " [W/M]: ");
choice = input.nextLine();
if (choice.length() == 1)
{
option = choice.charAt(0); //pick the first character
if (option == 'w' || option == 'W')
{
System.out.println("\n\tEnter name, ID and hours: ");
String name = input.nextLine();
System.out.print(" ");
String id = input.nextLine();
System.out.print(" ");
double hours = input.nextDouble();
a[i] = new Worker(name, id, hours);
System.out.println();
}
if (option == 'm' || option == 'M')
{
System.out.print("\n\tEnter name, ID, hours and pieces: ");
String name = input.nextLine();
System.out.print(" ");
String id = input.nextLine();
System.out.print(" ");
double hours = input.nextDouble();
System.out.print(" ");
double pieces = input.nextDouble();
b[i] = new MachineWorker(name, id, hours, pieces);
System.out.println();
}
System.out.print("\tType of object " + (i+1) + " [W/M]: ");
choice = input.nextLine();
}
a[i].displaySalary();
b[i].displaySalary();
b[i].productivityBonus();
}
}
}
You might want to use overriden methods readfromInput and displaySalary to distinguish between what Worker and Machinworker does.
The different behaviour should be implemented within the classes and not in the calling Polyworker class.
If Machineworker displaySalary shows the bonus this should be called in displaySalary of MachineWorker
see modified code below
//Worker.java
import java.util.Scanner;
/**
* a generic worker
*/
public class Worker {
public final double bonus = 100;
protected String name, workerID;
protected double hourlyRate, totalHoursWorked, tax, grossSalary, netSalary;
public void addWeekly(double hoursWorked) {
this.totalHoursWorked = this.totalHoursWorked + hoursWorked;
}
public double gross() {
grossSalary = (totalHoursWorked * hourlyRate);
if (totalHoursWorked >= 150) {
grossSalary = grossSalary + 100;
}
return grossSalary;
}
public double netAndTax() {
netSalary = grossSalary;
if (grossSalary > 500) {
tax = (grossSalary - 500) * 0.3;
netSalary = (grossSalary - tax);
}
return netSalary;
}
public String getName() {
return this.name;
}
public String getWorkerID() {
return this.workerID;
}
public double getHourlyRate() {
return this.hourlyRate;
}
public double getTotalHours() {
return totalHoursWorked;
}
public double getGrossSalary() {
return grossSalary;
}
public void addToGross(double amt) {
grossSalary = grossSalary + amt;
}
public void displaySalary() {
System.out.print("Name: " + getName() + "\nID :" + getWorkerID()
+ "\nHourly Rate: " + getHourlyRate() + "\nTotalHours Worked"
+ getTotalHours() + "\nGross pay" + getGrossSalary() + "\nTax: "
+ netAndTax() + "\nNet Pay: " + netAndTax());
}
public void readFromInput(Scanner input) {
name = input.nextLine();
System.out.print(" ");
this.workerID= input.nextLine();
System.out.print(" ");
this.totalHoursWorked = input.nextDouble();
System.out.println();
}
} // Worker
//MachineWorker.java
import java.util.Scanner;
public class MachineWorker extends Worker {
private double targetAmount;
private double totalPieces, productivityBonus;
public void addWeekly(double hoursWorked, double weeklyAmount) {
totalHoursWorked = hoursWorked + totalHoursWorked;
totalPieces = weeklyAmount + totalPieces;
}
public double productivityBonus() {
productivityBonus = 100 + (totalPieces - targetAmount);
return productivityBonus;
}
public double gross() {
grossSalary = (totalHoursWorked * hourlyRate) + productivityBonus;
if (totalHoursWorked >= 150) {
grossSalary = grossSalary + bonus;
}
return grossSalary;
}
public void addToGross(double amt) {
amt = productivityBonus;
grossSalary = grossSalary + amt;
}
#Override
public void displaySalary() {
super.displaySalary();
System.out.println("Productivity Bonus " + productivityBonus);
}
#Override
public void readFromInput(Scanner input) {
super.readFromInput(input);
this.totalPieces = input.nextDouble();
}
}
//Polymorphism PolyWorker.java
import java.util.*;
public class PolyWorkers {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
Worker[] workers = new Worker[5];
char option = '0';
String choice;
for (int i = 0; i < 5; i++) {
System.out.print("\tType of object " + (i + 1) + " [W/M]: ");
choice = input.nextLine();
if (choice.length() == 1) {
option = choice.toLowerCase().charAt(0); // pick the first character
switch (option) {
case 'w': {
workers[i] = new Worker();
System.out.println("\n\tEnter name, ID and hours: ");
}
break;
case 'm': {
System.out.print("\n\tEnter name, ID, hours and pieces: ");
}
break;
} // switch
workers[i].readFromInput(input);
}
workers[i].displaySalary();
}
}
}
Your question states that you have to store the references in a common array, where as you are storing them in 2 different arrays a and b. As you have different arrays for different type of objects, you don't have the need to use instanceOf operator. More about instanceOf is here.
Also, you do not check for null while printing salary or bonus. As at any point of the loop, only one type of object will be created, one of a[i] or b[i] will be definitely null, causing a NullPointerException.
You need another loop after the one you have already written that will allow the user to input the worker's hours. This will presumably be a while loop that will continually ask for input. You would then choose some sort of input that would quit the loop. Inside the loop you ask for hours and take either 2 or 3 arguments.
At the moment you are not storing your Workers/MachineWorkers. You need to create an array to store them in. You also need to create either a base class or an interface that they will both extend/implement. This will allow you to create a single array to store them all.
You then loop through your array of Workers/MachineWorkers and when you find a matching id you use your instanceof to work out whether you need to pass 1 or 2 arguments. If it is a MachineWorker you should cast it as such and then call the appropriate method with 2 arguments.