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
Related
I am having trouble with a part of an assignment where i have a method to calculate the regular pay of an employee but if the hours worked is over 40 then the rest is overtime but in if the user types in 50 hours with a 10 dollar rate it will print out 500 but i want it to to only print out 40 of those 50 hours and take the rest as overtime.
package paytime;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
String firstName, lastName, choice;
double hoursWorked, hourlyWage, weeklyPay;
Employee one = new Employee();
System.out.print("Enter Y to process employee or any other key to end: ");
choice = scn.nextLine();
if (choice.equalsIgnoreCase("Y"))
{
System.out.print("Enter employee number: ");
int number = scn.nextInt();
while (!one.findEmpNumber(number))
{
System.out.print("Invlaid, enter a proper employee number: ");
number = scn.nextInt();
}
System.out.print("Enter first name: ");
firstName = scn.next();
System.out.print("Enter last name: ");
lastName = scn.next();
System.out.print("Enter hours worked: ");
hoursWorked = scn.nextDouble();
while (hoursWorked < 0)
{
System.out.print("Negative hours not allowed. Enter hours worked: ");
hoursWorked = scn.nextDouble();
}
System.out.print("Enter hourly wage: $");
hourlyWage = scn.nextDouble();
while (hourlyWage < 0 || hourlyWage > 100)
{
System.out.print("Negative wage is not allowed or wage entered is to high. Enter hourley wage: $");
hourlyWage = scn.nextDouble();
}
System.out.println(" ");
if (hoursWorked <= 40.0)
{
System.out.println("Worker " + number + " Paycheck Information: ");
System.out.println("Name is: " + firstName + " " + lastName);
System.out.println("Weekly Pay is: " + one.callWeeklyPay(hoursWorked = 40, hourlyWage));
System.out.println("Income Taxes is: " + one.callIncomeTax());
System.out.println("Net Pay is: " + one.callNetPay());
}
else if (hoursWorked > 40.0)
{
System.out.println("Worker " + number + " Paycheck Information: ");
System.out.println("Name is: " + firstName + " " + lastName);
System.out.println("Weekly Pay is: " + one.callWeeklyPay(hoursWorked, hourlyWage));
System.out.println("Income Taxes is: " + one.callIncomeTax());
System.out.println("Net Pay is: " + one.callNetPay());
System.out.println(" ");
System.out.println(" ");
System.out.println("Worker " + number + " Overtime Calculation");
System.out.println("Name is: " + firstName + " " + lastName);
System.out.println("Weekly Pay is: " + one.callOvertimePay());
}
}
else
{
System.out.println("Total number of Employees processed: ");
}
}
}
package paytime;
public class Employee {
private int empNumbers [] = {101, 103, 106, 109, 110, 113, 116, 118, 120};
public double weeklyPay, hoursWorked, hourlyWage, incomeTax, netPay, actualOvertimeHours, overtimePay, overtimeHours;
public double overtimeWage = hourlyWage * 1.5;
public boolean findEmpNumber(int number)
{
boolean found = false;
for (int sub = 0; sub < empNumbers.length; sub++)
{
if (number == empNumbers[sub])
{
found = true;
break;
}
}
return found;
}
private void calculateWeeklyPay(double hoursWorked, double hourlyWage) {
weeklyPay = hoursWorked * hourlyWage;
}
public double callWeeklyPay(double hoursWorked, double hourlyWage) {
calculateWeeklyPay(hoursWorked, hourlyWage);
return weeklyPay;
}
private void calculateIncomeTax() {
if (weeklyPay > 0.0 && weeklyPay <= 300.0)
{
incomeTax = weeklyPay * 0.10;
}
else if (weeklyPay > 300.1 && weeklyPay <= 400.0)
{
incomeTax = weeklyPay * 0.12;
}
else if (weeklyPay > 400.1 && weeklyPay <= 500.0)
{
incomeTax = weeklyPay * 0.15;
}
else if (weeklyPay > 500.1)
{
incomeTax = weeklyPay * 0.20;
}
}
public double callIncomeTax() {
calculateIncomeTax();
return incomeTax;
}
private void calculateNetPay() {
netPay = weeklyPay - incomeTax;
}
public double callNetPay() {
calculateNetPay();
return netPay;
}
private void calculateOvertimePay() {
overtimeHours = hoursWorked -40;
overtimePay = ovetimeHours * overtimeWage;
}
public double callOvertimePay() {
calculateOvertimePay();
return overtimePay;
}
}
When you call callWeeklyPay method subtract 40 from the hoursWorked.
one.callWeeklyPay(hoursWorked - 40, hourlyWage));
But I would suggest moving the logic of checking for overtimes(hours exceeding 40) inside the Employee class (callWeeklyPay method) itself.
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!
**this is what I have done so far. This program need me to display student info. There is no error when I run the program but the grade just isn't displayed. **
import java.io.*;
import java.math.MathContext;
class StudInfo {
public static DataInputStream d = new DataInputStream(System.in);
public static String matricNo[] = new String[100];
public static String name[] = new String[100];
public static int courseWorkMark []= new int[100];
public static int finalExamMark[] = new int [100];
public static String grade[] = new String[100];
public static double mark1;
public static double mark2;
public static int x = 1;
public static String sgrade;
public static int scourseWorkMark;
public static int sfinalExamMark;
//MENU
public static void main(String[] args)throws IOException {
menu();
}
public static void menu()throws IOException {
System.out.println("<<<-- MAIN MENU -->>>");
System.out.println("");
System.out.println("[1] Add\n[2] Edit\n[3] Delete\n[4] Search\n[5] View\n[6] Exit");
System.out.println("");
System.out.print("Select a menu: ");
int m = Integer.parseInt(d.readLine());
switch(m) {
case 1: //ADD DATA
addData();
break;
case 2: //EDIT DATA
editData();
break;
case 3: //DELETE DATA
DeleteData();
break;
case 4: //SEARCH DATA
SearchData();
break;
case 5: //VIEW DATA
viewData();
break;
case 6: //EXIT SYSTEM
break;
default:
break;
}
}
//DELETE
public static void DeleteData()throws IOException {
boolean result = false;
int index = 0;
spacing();
System.out.print("<<<-- DELETE RECORDS -->>>\n\n");
System.out.print("Search Student Matric Number: ");
String smatricNo = d.readLine();
for(int i=1;i<matricNo.length;i++) {
if(matricNo[i] !=null) {
if(smatricNo.equalsIgnoreCase(matricNo[i])) {
result = true;
index = i;
}
}
}
if(result == true) {
System.out.print("Matric: "+matricNo[index].toUpperCase()+ " ");
System.out.print("Name: "+name[index].toUpperCase()+ " ");
System.out.print("Course Work: "+courseWorkMark[index]+ " ");
System.out.print("Final Exam: "+finalExamMark[index]+ " ");
System.out.print("Grade: "+grade[index].toUpperCase()+ " ");
System.out.println("");
System.out.print("Are you sure to save this record?[y]-y/[n]-no: ");
String Ques = d.readLine();
if(Ques.equalsIgnoreCase("y")) {
matricNo[index] = null;
name[index] = null;
courseWorkMark[index] = 0;
finalExamMark[index] = 0;
grade[index] = null;
for(int j=index+1;j<matricNo.length;j++)
{
matricNo[j-1] = matricNo[j];
name[j-1] = name[j];
courseWorkMark[j-1] = courseWorkMark[j];
finalExamMark[j-1] = finalExamMark[j];
grade[j-1] = grade[j];
}
System.out.println("Record succesfully deleted!");
System.out.println("\n\n<Press Enter>");
String Ques1 = d.readLine();
spacing();
menu();
} else{
spacing();
menu();
}
} else{
System.out.print("Matric Number not found!");
System.out.println("\n\n<Press Enter>");
String Ques = d.readLine();
spacing();
menu();
}
}
//SEARCH
public static void SearchData()throws IOException {
boolean result = false;
int index=0;
spacing();
System.out.print("<<<-- SEARCH DATA -->>>\n\n");
System.out.print("Search Student Matric Number: ");
String smatricNo = d.readLine();
for(int i=1;i<matricNo.length;i++) {
if(matricNo[i] !=null) {
if(smatricNo.equalsIgnoreCase(matricNo[i])) {
result = true;
index = i;
}
}
}
if(result==true) {
System.out.print("Matric: " + matricNo[index].toUpperCase() + " ");
System.out.print("Name: " + name[index].toUpperCase() + " ");
System.out.print("Course Work: " + courseWorkMark[index] + " ");
System.out.print("Final Exam: " + finalExamMark[index] + " ");
System.out.print("Grade: " + grade[index].toUpperCase() + " ");
System.out.println("");
System.out.println("\n\n<Press Enter>");
String Ques = d.readLine();
spacing();
menu();
}else {
System.out.print("Matric Number not found!");
System.out.println("\n\n<Press Enter>");
String Ques = d.readLine();
spacing();
menu();
}
}
//ADD
public static void addData()throws IOException {
spacing();
System.out.print("<<<-- ADD DATA -->>>\n\n");
System.out.print("Student Matric Number: ");
String smatricNo = d.readLine();
System.out.print("Student Name: ");
String sname = d.readLine();
System.out.print("Course Work: ");
scourseWorkMark = Integer.parseInt(d.readLine());
System.out.print("Final Exam: ");
sfinalExamMark = Integer.parseInt(d.readLine());
Calculate();
System.out.print("Grade: " + sgrade);
String sgrade = d.readLine();
System.out.print("Are you sure to save this record?[y]-y/[n]-no: ");
String Ques = d.readLine();
if(Ques.equalsIgnoreCase("y")) {
matricNo[x] = smatricNo;
name[x] = sname;
courseWorkMark[x] = scourseWorkMark;
finalExamMark[x] = sfinalExamMark;
grade[x] = sgrade;
x++;
spacing();
menu();
}else if(Ques.equalsIgnoreCase("n")) {
spacing();
menu();
}
}
public static void spacing() {
System.out.print("\n\n\n");
}
//VIEW
public static void viewData()throws IOException {
boolean center = false;
spacing();
System.out.print("<<<-- VIEW DATA -->>>\n\n");
for(int i=1;i<matricNo.length;i++) {
if(matricNo[i] != null) {
System.out.print("Matric Number: " + matricNo[i].toUpperCase()+ " ");
System.out.print("Name: " + name[i].toUpperCase()+ " ");
System.out.print("Course Work: " + courseWorkMark[i]+ " ");
System.out.print("Final Exam: " + finalExamMark[i]+ " ");
System.out.print("Grade: " + grade[i].toUpperCase()+ " ");
System.out.println("");
center=true;
}
}
if(center == false) {
System.out.print("\nEMPTY DATABASE. NO RECORDS FOUND!");
}
System.out.println("\n\n<Press Enter>");
String Ques = d.readLine();
spacing();
menu();
}
//EDIT
public static void editData()throws IOException {
boolean result = false;
int index=0;
spacing();
System.out.print("<<<-- EDIT DATA -->>>\n\n");
System.out.print("Search Matric Number: ");
String smatricNo = d.readLine();
for(int i=1;i<matricNo.length;i++) {
if(matricNo[i] !=null) {
if(smatricNo.equalsIgnoreCase(matricNo[i])) {
result = true;
index = i;
}
}
}
if(result == true) {
System.out.print(matricNo[index] + " " +name[index]+ " " +courseWorkMark[index]+ " " +finalExamMark[index]+ " " +grade[index]+ " \n\n");
System.out.print("Student Matric Number: ");
String smatricNoedit = d.readLine();
System.out.print("Student Name: ");
String snameedit = d.readLine();
System.out.print("Course Work: ");
scourseWorkMark = Integer.parseInt(d.readLine());
System.out.print("Final Exam: ");
sfinalExamMark = Integer.parseInt(d.readLine());
Calculate();
System.out.print("Grade: " + sgrade);
String sgrade = d.readLine();
System.out.print("Are you sure to update this record?[y]-y/[n]-no: ");
String Ques = d.readLine();
if(Ques.equalsIgnoreCase("y")) {
matricNo[index] = smatricNoedit;
name[index] = snameedit;
courseWorkMark[index] = scourseWorkMark;
finalExamMark[index] = sfinalExamMark;
grade[index] = sgrade;
spacing();
menu();
}
else if(Ques.equalsIgnoreCase("n"))
{
spacing();
menu();
}
}else {
System.out.print("Matric Number not found!");
System.out.println("\n\n<Press Enter>");
String Ques = d.readLine();
spacing();
menu();
}
}
//CALCULATION PART
public static String Calculate()
{
double mark1 = scourseWorkMark * 60 / 100;
double mark2 = sfinalExamMark * 40 / 100;
double totalMark = mark1 + mark2;
if (totalMark >= 90)
{
sgrade = "A+";
}
else if (totalMark >= 80)
{
sgrade = "A";
}
else if (totalMark >= 70)
{
sgrade = "A-";
}
else if (totalMark >= 65)
{
sgrade = "B+";
}
else if (totalMark >= 60)
{
sgrade = "B";
}
else if (totalMark >= 55)
{
sgrade = "C+";
}
else if (totalMark >= 50)
{
sgrade = "C";
}
else if (totalMark >= 45)
{
sgrade = "D";
}
else if (totalMark >= 40)
{
sgrade = "E";
}
else
{
sgrade = "F";
}
return;
}
}
Why can't the grade be displayed?
In the public static String Calculate() function, you need to return return sgrade; and currently, you are not returning any object, but the method calls for the return of a string.
Also, remove String sgrade = d.readLine(); from line 199 (in the addData function). This is causing problems, because you are defining a new variable with the same name as a class variable, and not specifying which one to use on the next few lines.
When I fix this, here is the output:
<<<-- MAIN MENU -->>>
[1] Add [2] Edit [3] Delete [4] Search [5] View [6] Exit
Select a menu: 1
<<<-- ADD DATA -->>>
Student Matric Number: 1
Student Name: Jake Chasan
Course Work: 100
Final Exam: 100 Grade: A+
<<<-- VIEW DATA -->>>
Matric Number: 1 Name: JAKE Course Work: 100
Final Exam: 100 Grade: A+
I'm getting an illegal start of expression on my public String makeChange(int amount) { method here.
I'm making a change dispensing program, and am kind of stuck here, I think I'm going about doing it right but am getting this error.
package changedispenser;
public class ChangeDispenser {
private static int quarters, dimes, nickels, pennies;
private static int penniesLeft, nickelsLeft, dimesLeft, quartersLeft;
private static int pennyRollsAdded = 1;
private static int nickelRollsAdded = 1;
private static int dimeRollsAdded = 1;
private static int quarterRollsAdded = 1;
public static final int PENNIES_PER_ROLL = 50;
public static final int NICKELS_PER_ROLL = 40;
public static final int DIMES_PER_ROLL = 50;
public static final int QUARTERS_PER_ROLL = 40;
public static void main(String[] args) {
public String makeChange(int amount) {
if (amount > 99 || amount < 0) {
System.out.println("");
}
quarters = amount / 25;
amount = amount % 25;
dimes = amount / 10;
amount = amount % 10;
nickels = amount / 5;
amount = amount % 5;
pennies = amount;
do {
if (quarters != 0) {
System.out.print(" Quarters: " + quarters);
}
if (dimes != 0) {
System.out.print(" Dimes: " + dimes);
}
if (nickels != 0) {
System.out.print(" Nickels: " + nickels);
}
if (pennies != 0) {
System.out.println(" Pennies: " + pennies);
}
//Fix this so that it outputs the appropriate change IE: 23 cents is 2 dimes 3 pennies
System.out.println("Coins Left:");
System.out.println("Quarters: " + quartersLeft);
System.out.println("Dimes: " + dimesLeft);
System.out.println("Nickels: " + nickelsLeft);
System.out.println("Pennies: " + penniesLeft);
System.out.println("Rolls Added: ");
System.out.println("Quarters: " + quarterRollsAdded);
System.out.println("Dimes: " + dimeRollsAdded);
System.out.println("Nickels: " + nickelRollsAdded);
System.out.println("Pennies: " + pennyRollsAdded);
} while (amount > 0 && amount <= 99);
return "Quarters: " + quarters + " Dime: " + dimes + " Nickels: " + nickels + " Pennies: " + pennies;
}
public int getPenniesLeft() {
return penniesLeft;
}
public void setPenniesLeft(int penniesLeft) {
this.penniesLeft = penniesLeft;
if (penniesLeft <= 0) {
pennyRollsAdded = pennyRollsAdded++;
}
}
public int getNickelsLeft() {
return nickelsLeft;
}
public void setNickelsLeft(int nickelsLeft) {
this.nickelsLeft = nickelsLeft;
if (nickelsLeft <= 0) {
nickelRollsAdded = nickelRollsAdded++;
}
}
public int getDimesLeft() {
return dimesLeft;
}
public void setDimesLeft(int dimesLeft) {
this.dimesLeft = dimesLeft;
if (dimesLeft <= 0) {
dimeRollsAdded = dimeRollsAdded++;
}
}
public int getQuartersLeft() {
return quartersLeft;
}
public void setQuartersLeft(int quartersLeft) {
this.quartersLeft = quartersLeft;
if (quartersLeft <= 0) {
quarterRollsAdded = quarterRollsAdded++;
}
}
public int getPennyRollsAdded() {
return pennyRollsAdded;
}
public void setPennyRollsAdded(int pennyRollsAdded) {
this.pennyRollsAdded = pennyRollsAdded;
}
public int getNickelRollsAdded() {
return nickelRollsAdded;
}
public void setNickelRollsAdded(int nickelRollsAdded) {
this.nickelRollsAdded = nickelRollsAdded;
}
public int getDimeRollsAdded() {
return dimeRollsAdded;
}
public void setDimeRollsAdded(int dimeRollsAdded) {
this.dimeRollsAdded = dimeRollsAdded;
}
public int getQuarterRollsAdded() {
return quarterRollsAdded;
}
public void setQuarterRollsAdded(int quarterRollsAdded) {
this.quarterRollsAdded = quarterRollsAdded;
}
}
new code, here it is
package changedispenser;
public class ChangeDispenser {
private static int quarters, dimes, nickels, pennies;
private static int penniesLeft, nickelsLeft, dimesLeft, quartersLeft;
private static int pennyRollsAdded = 1;
private static int nickelRollsAdded = 1;
private static int dimeRollsAdded = 1;
private static int quarterRollsAdded = 1;
public static final int PENNIES_PER_ROLL = 50;
public static final int NICKELS_PER_ROLL = 40;
public static final int DIMES_PER_ROLL = 50;
public static final int QUARTERS_PER_ROLL = 40;
public static void main(String[] args) {
if (quarters != 0) {
System.out.print(" Quarters: " + quarters);
}
if (dimes != 0) {
System.out.print(" Dimes: " + dimes);
}
if (nickels != 0) {
System.out.print(" Nickels: "+ nickels);
}
if (pennies !=0) {
System.out.println(" Pennies: " + pennies);
}
}
ChangeDispenser() {
quartersLeft = QUARTERS_PER_ROLL;
dimesLeft = DIMES_PER_ROLL;
nickelsLeft = NICKELS_PER_ROLL;
penniesLeft = PENNIES_PER_ROLL;
pennyRollsAdded = 1;
nickelRollsAdded = 1;
dimeRollsAdded = 1;
quarterRollsAdded = 1;
}
public int getPenniesLeft() {
return penniesLeft;
}
public void setPenniesLeft(int penniesLeft) {
this.penniesLeft = penniesLeft;
if (penniesLeft <= 0) {
pennyRollsAdded = pennyRollsAdded++;
}
}
public int getNickelsLeft() {
return nickelsLeft;
}
public void setNickelsLeft(int nickelsLeft) {
this.nickelsLeft = nickelsLeft;
if (nickelsLeft <= 0) {
nickelRollsAdded = nickelRollsAdded++;
}
}
public int getDimesLeft() {
return dimesLeft;
}
public void setDimesLeft(int dimesLeft) {
this.dimesLeft = dimesLeft;
if (dimesLeft <= 0) {
dimeRollsAdded = dimeRollsAdded++;
}
}
public int getQuartersLeft() {
return quartersLeft;
}
public void setQuartersLeft(int quartersLeft) {
this.quartersLeft = quartersLeft;
if (quartersLeft <= 0) {
quarterRollsAdded = quarterRollsAdded++;
}
}
public int getPennyRollsAdded() {
return pennyRollsAdded;
}
public void setPennyRollsAdded(int pennyRollsAdded) {
this.pennyRollsAdded = pennyRollsAdded;
}
public int getNickelRollsAdded() {
return nickelRollsAdded;
}
public void setNickelRollsAdded(int nickelRollsAdded) {
this.nickelRollsAdded = nickelRollsAdded;
}
public int getDimeRollsAdded() {
return dimeRollsAdded;
}
public void setDimeRollsAdded(int dimeRollsAdded) {
this.dimeRollsAdded = dimeRollsAdded;
}
public int getQuarterRollsAdded() {
return quarterRollsAdded;
}
public void setQuarterRollsAdded(int quarterRollsAdded) {
this.quarterRollsAdded = quarterRollsAdded;
}
public String makeChange(int amount) {
if (amount > 99 || amount < 0) {
System.out.println("");
}
quarters = amount / 25;
amount = amount % 25;
dimes = amount / 10;
amount = amount % 10;
nickels = amount / 5;
amount = amount % 5;
pennies = amount;
do {
if (quarters != 0) {
System.out.print(" Quarters: " + quarters);
}
if (dimes != 0) {
System.out.print(" Dimes: " + dimes);
}
if (nickels != 0) {
System.out.print(" Nickels: " + nickels);
}
if (pennies != 0) {
System.out.println(" Pennies: " + pennies);
}
} while (amount > 0 && amount <= 99);
return "Quarters: " + quarters + " Dime: " + dimes + " Nickels: " + nickels + " Pennies: " + pennies;
}
public void writeReport() {
System.out.println("Coins Left:");
System.out.println("Quarters: " + quartersLeft);
System.out.println("Dimes: "+ dimesLeft);
System.out.println("Nickels: " + nickelsLeft);
System.out.println("Pennies: " +penniesLeft);
System.out.println("Rolls Added: ");
System.out.println("Quarters: "+ quarterRollsAdded);
System.out.println("Dimes: " + dimeRollsAdded);
System.out.println("Nickels: " + nickelRollsAdded);
System.out.println("Pennies: " + pennyRollsAdded);
}
}
Here is a seperate driver class to run the program.
package changedispenser;
import java.util.Random;
public class ChangeDispenserDriver {
public static void main(String[] args) {
ChangeDispenser changeMachine = new ChangeDispenser();
Random rand = new Random();
int amount;
for (int i = 0; i < 1000; i++) {
amount = rand.nextInt(99) + 1;
System.out.println("Amount: " + amount + ": Change = " + changeMachine.makeChange(amount));
}
changeMachine.writeReport();
}
}
You're creating a method inside of another method, a no-no:
public static void main(String[] args) {
public String makeChange(int amount) {
This is one place where good code formatting helps. Your formatting is not so good with lack of regular and sensible indentation. Put in the effort to format your code well and it will pay you dividends.
For instance, you'd see immediately:
public static void main(String[] args) {
public String makeChange(int amount) {
//...
}
// ...
}
... that you're nesting methods.
Edit:
Regarding your latest code, I can't say that I went through all of it, but this is very dangerous:
do {
if (quarters != 0) {
System.out.print(" Quarters: " + quarters);
}
if (dimes != 0) {
System.out.print(" Dimes: " + dimes);
}
if (nickels != 0) {
System.out.print(" Nickels: " + nickels);
}
if (pennies != 0) {
System.out.println(" Pennies: " + pennies);
}
} while (amount > 0 && amount <= 99);
Your loop depends on amount changing to a value that allows the loop to end, but where do you actually change amount inside of the loop? If you don't change amount inside of the loop, how will it ever exit the loop. You don't, and so the loop could (and does) loop forever.
Hovercraft is right, the way you would fix it is to separate them
public static void main (String[]args){
System.out.println(makeChange(5));
}
public String makeChange(int amount){
....
}
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.