Updating variable in a While Loop - java

I'm having some problem with a household budget application.After I insert a new income or bill, checking the budget, the program add even the previous bill (or income) as commented in the Client code.
public class Client {
public static void main(String[] args) {
Budget bud = new Budget();
Bills[] expenses = new Bills[10];
Income[] salary = new Income[4];
boolean toContinue = true;
String input = "";
int menuItem = 0;
int counter = 0;
int salCount = 0;
float budget = 0;
while (toContinue) {
input = JOptionPane
.showInputDialog("(1) Add an expense\n(2) Add the salary\n(3) Display Current Budget\n(4) Exit");
menuItem = Integer.parseInt(input);
switch (menuItem) {
case 1: //Add expense
String name = JOptionPane.showInputDialog("Enter the name of the expense");
double amount = Double.parseDouble(JOptionPane.showInputDialog("Enter the amount for " + name));
expenses[counter++] = new Bills(name, amount);
break;
case 2: //Add salary
String checkSal = JOptionPane.showInputDialog("Enter salary details");
double checkAm = Double.parseDouble(JOptionPane.showInputDialog("Enter the amount of " + checkSal));
salary[salCount++] = new Income(checkSal, checkAm);
break;
case 3: // display current budget
try {
String expDisplay = "Expenditure\t Amount\n";
String salDisplay = "Salary\t Amount\n";
float expenseSum = 0;
float salarySum = 0;
for (int i = 0; i < salary.length; i++) {
if (salary[i] != null)
salarySum += salary[i].Total();
}
for (int e = 0; e < expenses.length; e++) {
if (expenses[e] != null)
expenseSum += expenses[e].Total();
}
for (Bills e : expenses) {
if (e != null)
expDisplay += e.toString() + "\n";
}
for (Income p : salary) {
if (p != null)
salDisplay += p.toString() + "\n";
}
File fileBudget = new File("C:budget.txt");
if (!fileBudget.exists()) { //creating new txt
bud.setBudget(budget);
fileBudget.createNewFile();
System.out.println("TEXT File Created");
FileWriter fw = new FileWriter(fileBudget, false);
fw.write(bud.getBud() + "");
fw.flush();
fw.close();
budget = salarySum - expenseSum; //calculating budget
JOptionPane.showMessageDialog(null, expDisplay + "\n\n" + salDisplay + "\n\n" + "You spent: "
+ expenseSum + "\n" + "Budget: " + budget);
} else {
BufferedReader re = new BufferedReader(new FileReader("C:budget.txt")); //reading budget on txt file
while (true) {
String line = re.readLine();
if (line == null) {
break;
} else {
float d = Float.valueOf(line);
bud.setBudget(d); //store the read value
}
}
re.close(); //end reading
float c = bud.getBud(); //taking budget value
// problem...there are even previous sum values!!
budget = salarySum - expenseSum + c; // error
FileWriter fw = new FileWriter(fileBudget, false);
fw.write(budget + "\n");
fw.flush();
fw.close();
JOptionPane.showMessageDialog(null, expDisplay + "\n\n" + salDisplay + "\n\n" + "You spent: "
+ expenseSum + "\n" + "Budget: " + budget);
}
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
break;
case 4: //close program
JOptionPane.showMessageDialog(null, "You closed the Budget Program!");
System.exit(0); }}}}
//budget object
public class Budget implements Serializable {
private static final long serialVersionUID = 1L;
public float bud;
Budget()
{
}
public float getBud() {
return bud;
}
public void setBudget(float bud) {
this.bud = bud; }}
//Bill class
public class Bills {
private double amount;
private String name;
public Bills(double amount) {
this.amount = amount;
}
public Bills(String name, double amount) {
this.name = name;
this.amount = amount;
}
public Bills() {
this("New Expense", 0); }
public String toString() {
return name + "\t " + "\t " + amount; }
public double Total() {
return amount; }}
//Income class
public class Income {
private double amount;
private String Salary;
public Income(String Salary, double amount) {
this.Salary = Salary;
this.amount = amount;
}
public String toString() {
return Salary + "\t " + "\t " + amount;
}
public double Total() {
return amount; }}

There are several problems with your code.
First of all here:
for (int i = 0; i < salary.length; i++)
{
if (salary[i] != null)
{
salarySum += salary[i].Total();
}
}
for (int e = 0; e < expenses.length; e++)
{
if (expenses[e] != null)
{
expenseSum += expenses[e].Total();
}
}
Each time your user enter [3] to see the details, these numbers added, and then the budget is calculated, this budget then is added to the file.
On the same session now, the user click again [3] and the above is repeated.
You should find a way to actually identify when the user have enter a new expense or a new salary, to avoid repeating the calculation of the budget and then the assignment to the file. (Boolean variable probably?)
Moreover here:
if (!fileBudget.exists()) { //creating new txt
bud.setBudget(budget);
fileBudget.createNewFile();
System.out.println("TEXT File Created");
FileWriter fw = new FileWriter(fileBudget, false);
fw.write(bud.getBud() + "");
fw.flush();
fw.close();
budget = salarySum - expenseSum; //calculating budget
JOptionPane.showMessageDialog(null, expDisplay + "\n\n" + salDisplay + "\n\n" + "You spent: "
+ expenseSum + "\n" + "Budget: " + budget);
}
You always assign a zero value to the file. Even if the file is going to be created, maybe the user have already provided some budget, and you will lose this number. I think you have to calculate the budget there as well.
Edit:
A possible solution, and to simplify things, is to actually add to the file whenever the user enter a new salary, and subtract from the file whenever user enter an expense, so these two actions will take place in the first two cases (1 and 2) of the select statement. (Both actions, require that you read the text value first and then you add the new salary or you then subtract the new expense). This way your file will contain the latest calculated budget, and in the 3rd case you will only read the value from the file, which will contain the latest calculated budget, rather than calculating the budget in the 3rd case every time!

Related

Incorrect Math In Program, not sure why?

I am writing a simple program for class. I am not sure why the math is not showing correctly? When I ask for a tax and input 0.08 it is not computing to the right number. For example entering 1234.55 as the retail amount gives a transaction amount of 1266.6483 instead of the correct amount which should be 1333.31. Any help would be appreciated... I'll post the code below
package Project03Driver;
import java.io.*;
public class Project03Driver
{
public static void main(String args[]) throws IOException
{
Project03 app;
app = new Project03();
app.appMain();
}
}
class Project03
{
BufferedReader stdin;
int tNum, tCount, smallTnum;
double tax, rA, tA, raTot, disTot, taTot, taAvg, smallTa;
boolean disc;
String store, date, dFlag, inString;
public void appMain() throws IOException
{
rptInit();
displayHeader();
getStore();
while(tNum != 0)
{
salesData();
}
calcAvg();
rptOut();
}
void rptInit()
{
tNum = 1;
tCount = smallTnum = 0;
raTot = disTot = taTot = taAvg = 0;
smallTa = 10000;
stdin = new BufferedReader (new InputStreamReader(System.in));
}
void displayHeader()
{
System.out.println("Project #03 Solution");
System.out.println("Written by Jordan Hawkes");
}
void getStore() throws IOException
{
System.out.println("Enter Store: ");
store = stdin.readLine();
System.out.println("Enter Date: ");
date = stdin.readLine();
System.out.println("Enter Tax as Decimal (ex. .05): ");
tax = Double.parseDouble(stdin.readLine());
}
void salesData() throws IOException
{
getTransNum();
if (tNum != 0)
{
inputRa();
calcSalesData();
outputSalesData();
}
}
void getTransNum() throws IOException
{
System.out.println("Enter Transaction Number: ");
tNum = Integer.parseInt(stdin.readLine());
}
void inputRa() throws IOException
{
System.out.println("Enter Retail Amount: ");
rA = Double.parseDouble(stdin.readLine());
}
void calcSalesData()
{
tCount = tCount + 1;
raTot = raTot + rA;
if (tA > 1500)
{
disc = true;
dFlag = "Discounted";
}
else
{
disc = false;
dFlag = "No";
}
transAmt();
discTot();
taTot = taTot +tA;
smallTrans();
}
void transAmt()
{
if (disc = true)
{
tA = (rA * 0.95) + ((rA * 0.95) * tax);
}
else
{
tA = (rA * tax) + rA;
}
}
void discTot()
{
if (disc = true)
{
disTot = disTot + (tA - rA);
}
else
{
disTot = disTot;
}
}
void smallTrans()
{
if (tA < smallTa)
{
smallTa = tA;
smallTnum = tNum;
}
}
void outputSalesData()
{
System.out.println("");
System.out.println("--------------------------------------------");
System.out.println("Transaction Number: " + tNum);
System.out.println("Retail Amount: " + rA);
System.out.println("Discount Flag: " + dFlag);
System.out.println("Transaction Amount: " + tA);
System.out.println("--------------------------------------------");
System.out.println("");
}
void calcAvg()
{
taAvg = taTot / tCount;
}
void rptOut()
{
System.out.println("");
System.out.println("--------------------------------------------");
System.out.println("Store: " + store);
System.out.println("Date: " + date);
System.out.println("Tax Rate: " + tax);
System.out.println("--------------------------------------------");
System.out.println("Retail Amount Total: " + raTot);
System.out.println("Discount Total: " + disTot);
System.out.println("Transaction Amount Total: " + taTot);
System.out.println("Average Transaction Amount: " + taAvg);
System.out.println("Smallest Transaction Amount: " + smallTa);
System.out.println("Smallest Transaction Number: " + smallTnum);
System.out.println("--------------------------------------------");
}
}
if (disc = true)
should be
if (disc == true)
I think you should delete the question, because that is a typo. According to https://stackoverflow.com/help/on-topic

How can I get my program back on track when printing out all student records?

import java.util.Scanner;
public class MainBinaryTreeArray
{
public static void main(String[] args)
{
int choice;
Scanner scan= new Scanner(System.in);
BinaryTreeArray data = new BinaryTreeArray();
Listing l1 = new Listing("Carol", 4354, 3.2);
Listing l2 = new Listing("Timothy", 2353, 4.0);
Listing l3 = new Listing("Dean", 4544, 2.4);
Listing l4 = new Listing("Sue", 3445, 3.0);
data.insert(l1);
data.insert(l2);
data.insert(l3);
data.insert(l4);
do
{
// Choose which operation by entering a number
System.out.println("*****************(Menu Operations:)******************");
System.out.println(" (Press 1). Insert.");
System.out.println(" (Press 2). Fetch.");
System.out.println(" (Press 5). Output all student records.");
System.out.println(" (Press 6). Exit the program.");
System.out.println("Enter your choice: ");
choice = scan.nextInt();
switch(choice)
{
case 1:
System.out.println("Are students inserted: " + data.insert(l1));
break;
case 2:
System.out.println("The student's info that's fetched: ");
System.out.print(data.fetch("Timothy"));
break;
case 5:
System.out.print("Output all the student's records: ");
data.showAll();
}
}while(choice!=6);
}
}
public class BinaryTreeArray
{
private Listing[] data;
private int size;
public BinaryTreeArray()
{
size = 100;
data = new Listing[size];
}
public void showAll()
{
for(int i=0; i<size; i++)
System.out.print(data[i] + " ");
}
public boolean insert(Listing newListing)
{
int i = 0;
while(i < size && data[i]!= null)
{
if(data[i].getKey().compareTo(newListing.getKey()) > 0)
i = 2 * i + 1;
else
i = 2 * i + 2;
}
if(i >= size)
return false;
else
{
data[i] = newListing.deepCopy();
return true;
}
}
public Listing fetch(String targetKey)
{
int i= 0;
while(i< size && data[i]!= null && data[i].getKey()!=targetKey)
{
if(data[i].getKey().compareTo(targetKey) > 0)
i = 2 * i + 1;
else
i = 2 * i + 2;
}
if(i >= size || data[i] == null)
return null;
else
return data[i].deepCopy();
}
}
public class Listing implements Comparable<Listing>
{ private String name; // key field
private int ID;
private double GPA;
public Listing(String n, int id, double gpa)
{ name = n;
ID = id;
GPA = gpa;
}
public String toString()
{ return("Name is " + " " + name +
"\nID is" + " " + ID +
"\nGPA is" + " " + GPA + "\n");
}
public Listing deepCopy()
{ Listing clone = new Listing(name, ID, GPA);
return clone;
}
public int compareTo(Listing other)
{
return this.name.compareTo(other.getKey());
}
public String getKey()
{
return name;
}
}// end of class Listing
Hello All,
My java program compiles fine, but I am having a terrible and miserable time with getting my program to stop printing all those nulls when I output all student records in my BinaryTreeArray. Here is complete program. Any suggestions? Please do give any advice. So to make what I am saying clear, I need help with understanding why when I print out student records it includes a whole bunch of extra nulls that really have no purpose and just make my program look crazy. Any solutions to this problem?
When you initialize the BinaryTreeArray(), you set the field variable "size" to 100 and use this to initialize the data Listing[] array. When you print out the data, the loop uses the same "size" variable so you get all 100 entries, including the null entries. A simple solution would be to filter the data for null when you show all.
public class BinaryTreeArray
{
...
public void showAll()
{
for(int i=0; i<size; i++)
{
if (data[i] != null)
System.out.print(data[i] + " ");
}
}
...
}
An alternate solution would be to change your use of size to maxSize and then create a variable size that is incremented as you insert listings.

How to get the total of each column

Its been a ridiculous task especially to build the total of each vertical column & to show it on screen. Though, calculating the total of horizontal row never seemed to be a challenge.
The problem I'm having is three-fold.
How do I calculate the total of each vertical column ?
The index (id) is getting printed in descending order. How do I make it print in ascending order ?
Further, in the percentage column the value after the decimal point is being discarded. How do I get that displayed? For eg.. if
answer is supposed to be 78.25% it exhibits as 78.0%
P.S : (2 places after the decimal point is what I'm aiming at.)
POJO class -- StudentsProg.java
package com.students.marks;
import java.util.Arrays;
public class StudentsProg {
private int id = 0;
private String name;
private int english;
private int german;
private int french;
private int arabic;
private double percentage;
private int total_marks;
private int rowHighest;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getEnglish() {
return english;
}
public void setEnglish(int english) {
this.english = english;
}
public int getGerman() {
return german;
}
public void setGerman(int german) {
this.german = german;
}
public int getFrench() {
return french;
}
public void setFrench(int french) {
this.french = french;
}
public int getArabic() {
return arabic;
}
public void setArabic(int arabic) {
this.arabic = arabic;
}
public double getPercentage() {
return percentage;
}
public void setPercentage(double percentage) {
this.percentage = percentage;
}
public int getTotal_marks() {
return total_marks;
}
public void setTotal_marks(int total_marks) {
this.total_marks = total_marks;
}
public int getRowHighest() {
return rowHighest;
}
public void setRowHighest(int rowHighest) {
this.rowHighest = rowHighest;
}
public String toString() {
id = id+1;
return (id + "\t" +name+ "\t\t" +english+ "\t" + " " +german+ "\t" + " "+ french+ "\t" + " " +arabic+ "\t" +" " +total_marks+ "\t\t" + " " +percentage+ "\t\t" +rowHighest);
}
}
StudentsProgMain.java
import java.util.Scanner;
public class StudentsProgMain {
#SuppressWarnings("resource")
public static void main(String[] args) {
int count = 0;
StudentsProg[] stud = new StudentsProg[15];
int choice=0;
int max = 0;
Scanner scanner = new Scanner(System.in);
do{
System.out.println("1: Add new Student");
System.out.println("2: List Student");
System.out.println("3: List Student By Name.");
System.out.println("4: Delete Student");
System.out.println("5: Exit");
System.out.println("Please enter your choice \n\n");
choice=scanner.nextInt();
switch(choice){
case 1:
stud[count] = new StudentsProg();
System.out.println("Enter student name");
stud[count].setName(scanner.next());
System.out.println("Enter marks in English");
stud[count].setEnglish(scanner.nextInt());
System.out.println("Enter marks in German");
stud[count].setGerman(scanner.nextInt());
System.out.println("Enter marks in French");
stud[count].setFrench(scanner.nextInt());
System.out.println("Enter marks in Arabic");
stud[count].setArabic(scanner.nextInt());
count++;
break;
case 2:
System.out.println("ID\t" + "Name \t\t\t" + "English\t" + " " + "German\t"+ " " + "French\t" + " " + "Arabic\t"
+" "+ "Total Marks\t" + " " + "Percentage\t" + "Highest Marks(Row)\n" +
"------------------------------------------------------------------------"
+ "------------------------------------------- \n ");
for(int i=0; i<count; i++){
if(stud[i]!=null){
int total_marks = stud[i].getEnglish()+stud[i].getGerman()+ stud[i].getFrench()+stud[i].getArabic();
stud[i].setTotal_marks(total_marks);
double calc_per = ((total_marks*100)/400);
stud[i].setPercentage(calc_per);
int arrayListMarks [] = {stud[i].getEnglish(), stud[i].getFrench(), stud[i].getGerman(), stud[i].getArabic()};
max = arrayListMarks[0];
for (int j = 1; j < arrayListMarks.length; j++) {
if(arrayListMarks[j] > max)
max = arrayListMarks[j]; }
stud[i].setRowHighest(max);
System.out.println(stud[i].toString());
System.out.println("\n");}
}
System.out.println("--------------------------------------------------------------"
+ "----------------------------------------------------- \n");
System.out.println("\tTotal :" +"\n");
break;
case 3 :
System.out.println("Please enter your name");
String name = scanner.next();
System.out.println("\n" + "ID\t" + "Name \t\t\t" + "English\t" + " " + "German\t"+ " " + "French\t" + " " + "Arabic\t"
+" "+ "Total Marks\t" + " " + "Percentage\t" + "Highest Marks(Row)\n" +
"------------------------------------------------------------------------"
+ "------------------------------------------- \n ");
for(int i =0 ; i<count; i++){
if(stud[i]!=null && stud[i].getName().equals(name))
System.out.println(stud[i].toString()); }
System.out.println("--------------------------------------------------------------"
+ "----------------------------------------------------- \n");
break;
case 4 :
System.out.println("Please enter your name");
String naam = scanner.next();
for (int i = 0; i<count; i++) {
if(stud[i]!=null && stud[i].getName()==naam)
stud[i]=null;
}
break;
case 5:
System.exit(0);
System.out.println("You have exited successfully");
default :
System.out.println("Invalid choice");
}
}while(true);
}
}
The problem with the percentage calculation is that the line of code double calc_per = ((total_marks*100)/400); will do integer arithmetic and truncate each intermediate result as an integer. To fix this you need to include a floating point number somewhere in the calculation either by converting total_marks to double like so:
double calc_per = ((Integer.valueOf(total_marks).doubleValue()*100)/400);
Or using a float constant like so:
double calc_per = ((total_marks*100.0)/400);
Vertical totals should just be a matter of adding the row value to a variable inside your print loop.
I'm not really sure about your index order problem but the code in toString() that reads id = id+1; looks wrong. This will increment the Id each time you call toString(). Instead of that, your creation code should set the value of id just after creating the object, something like:
stud[count] = new StudentsProg();
// add the following line of code.
stud[count].setId(count);
System.out.println("Enter student name");
stud[count].setName(scanner.next());

My code is not printing

my code (reads a text file, uses a class I built to sort through the data, and then outputs onto console), is not printing anything! Can somebody please tell me where my little mistake is! I know the VERY end is not finished yet. Please help!!!!!!!!
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class Project02 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<Product> products = new ArrayList<Product>();
// Enter file name
System.out.print("Enter database file name: ");
String fileName = in.nextLine();
try {
File file = new File(fileName);
Scanner inputFile = new Scanner(file);
System.out.println();
while (inputFile.hasNext()) {
Product p = new Product();
String title = inputFile.nextLine();
String code = inputFile.nextLine();
Integer quantity = inputFile.nextInt();
Double price = inputFile.nextDouble();
inputFile.nextLine();
String type = inputFile.nextLine();
Integer userReview = inputFile.nextInt();
// read in title
p.setName(title);
// read in iCode
p.setInventoryCode(code);
// read in quantity
p.setQuantity(quantity);
// read in price
p.setPrice(price);
// read in type
p.setType(type);
// read in user reviews
while (!userReview.equals(-1)) {
p.addUserRating(userReview);
userReview = inputFile.nextInt();
}
if (inputFile.hasNext()) {
inputFile.nextLine();
}
}
inputFile.close();
} catch (IOException e) {
System.out.println("There was an error reading from " + fileName);
}
}
private static String highRating(ArrayList<Product> p) {
int highestR = 0;
int indexOfHighestR = 0;
for (int i = 0; i < p.size(); i++) {
int rating = p.get(i).getAvgUserRating();
if (p.get(i).getAvgUserRating() > highestR) {
highestR = p.get(i).getAvgUserRating();
indexOfHighestR = i;
}
}
int zero = 0;
String Star = " ";
while (highestR > zero) {
Star = Star + "*";
zero--;
}
String highestRateTitle = p.get(indexOfHighestR).getName() + " ("
+ Star + ")";
return highestRateTitle;
}
private static String lowestRating(ArrayList<Product> p) {
int lowestR = 0;
int indexOfLowestR = 0;
for (int i = 0; i < p.size(); i++) {
int rating = p.get(i).getAvgUserRating();
if (p.get(i).getAvgUserRating() < lowestR) {
lowestR = p.get(i).getAvgUserRating();
indexOfLowestR = i;
}
}
int zero = 0;
String Star = " ";
while (lowestR > zero) {
Star = Star + "*";
zero--;
}
String highestRateTitle = p.get(indexOfLowestR).getName() + " ("
+ Star + ")";
return highestRateTitle;
}
private static double maxDollar(ArrayList<Product> p) {
double largestP = 0;
int indexOfLargestP = 0;
for (int i = 0; i < p.size(); i++) {
double price = p.get(i).getPrice();
if (p.get(i).getPrice() > largestP) {
largestP = p.get(i).getPrice();
indexOfLargestP = i;
}
}
return largestP;
}
private static int minDollar(ArrayList<Product> p) {
double smallestP = p.get(0).getPrice();
int indexOfSmallestP = 0;
for (int i = 0; i < p.size(); i++) {
if (p.get(i).getPrice() < smallestP) {
smallestP = p.get(i).getPrice();
indexOfSmallestP = i;
}
}
return indexOfSmallestP;
}
private static void inventoryList(ArrayList<Product> p) {
int count =
System.out.println("Product Summary Report: ");
System.out
.println("------------------------------------------------------------");
for (int i = 0; i < count; i++) {
System.out.println("Title: " + p.get(i).getName());
System.out.println("I Code: " + p.get(i).getInventoryCode());
System.out.println("Product Type: " + p.get(i).getType());
System.out.println("Rating: " + p.get(i).getAvgUserRating());
System.out.println("# Rat.: " + p.get(i).getUserRatingCount());
System.out.println("Quantity: " + p.get(i).getQuantity());
System.out.println("Price: " + p.get(i).getPrice());
System.out.println();
}
System.out
.println("-----------------------------------------------------------------");
// System.out.println("Total products in database: " + count);
System.out.println("Highest total dollar item: "
+ p.get(maxDollar(p)) + " ($"+ p.(maxDollar(p)) + ")");
System.out.println("Smallest quantity item: "
+ p.get(minQuantity(quantities)) + " ("
+ types.get(minQuantity(quantities)) + ")");
System.out.println("Lowest total dollar item: "
+ titles.get(minDollar(prices)) + " ($"
+ prices.get(minDollar(prices)) + ")");
System.out
.println("-----------------------------------------------------------------");
}
First...
After you've create an instance of Product, p, you will need to add it to the products list, otherwise you will lose it's reference and won't be able to use it again...
while (inputFile.hasNext()) {
Product p = new Product();
//...
products.add(p);
if (inputFile.hasNext()) {
inputFile.nextLine();
}
}
Second...
You will need to pass the products List to something that want's to use/display the information, for example inventoryList...
But wait, that's not working?
If we take a closer look at the the inventoryList method...
int count = 0;
//...
for (int i = 0; i < count; i++) {
We can see that count is always 0, so it will never print anything! You should be using p.size() instead, which is the actually length of the products List
//...
for (int i = 0; i < p.size(); i++) {

Polymorphism and instanceof

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.

Categories

Resources