Try to reset tip back to 0 at the end of the do loop so it can accept a new value without adding the previous value.
tip = 0;
or you could create a tip array and store each tip value in the array
Question
Alright well I have one method that gets the name and wage of a worker.. in my class definition I have where it creates an object whether they input nothing, a name, or a name and wage.
So then for each worker I need to ask for tips (which there can be multiple clients who tip). I have this in another method and I prompt for the tip but I'm not sure how to only add the tips to the specific worker.. ie. when I run the program, the output is correct for this first worker (salary, tips, avg tips) and if I add another worker the tips are wrong because it is not separated, rather it is continuing to add all the tips from each worker
private static void addWorker(){
name = JOptionPane.showInputDialog("Name?");
wage = Double.parseDouble(JOptionPane.showInputDialog(null,"Wage?"));
worker object = new worker(name, wage);
workerArray[count] = object;
addWorkerTip();
count++;
}
private static void addWorkerTip(){
do{
tip = Double.parseDouble(JOptionPane.showInputDialog(null,"tip?"));
numTips++;
totalWorkerTips = tip + totalWorkerTips;
worker.addTips(totalWorkerTips);
}while (JOptionPane.showConfirmDialog(null,"Another Worker?") == JOptionPane.YES_OPTION);
}
Pas de solution correcte
Autres conseils
Try to reset tip back to 0 at the end of the do loop so it can accept a new value without adding the previous value.
tip = 0;
or you could create a tip array and store each tip value in the array
You should make a class called worker with proper instance variables.
public class Worker{
private String name;
private double wage;
private double tip;
public Worker(){
name=null;
wage=null;
tip=0;
}
public Worker(String n){
name=n;
tip=0;
}
public Worker(String n, double w){
name = n;
wage = w;
tip=0;
}
public void setWage(double newWage){
wage = newWage;
}
public void addTip(double newTip){
tip+=newTip;
}
}
Here is how I would approach your class structure,
private static class Worker {
private String name;
private double wage;
private double tip = 0;
Worker(String name, double wage) {
this.name = name;
this.wage = wage;
}
public String getName() {
return name;
}
public double getWage() {
return wage;
}
public void addTip(double tip) {
this.tip += tip;
}
public double getTipe() {
return this.tip;
}
}
// Use a Collection of Worker(s) - not an array.
private List<Worker> workers = new ArrayList<Worker>();
public void addWorker() {
String name = JOptionPane.showInputDialog("Name?");
double wage = Double.parseDouble(JOptionPane
.showInputDialog(null, "Wage?"));
Worker worker = new Worker(name, wage);
double tip = Double.parseDouble(JOptionPane
.showInputDialog(null, "tip?"));
worker.addTip(tip);
workers.add(worker); // Add the worker to the List.
}