Calculation with clicking on a button within JTextArea - java

i am trying to create such calculation within a texArea which i calculate in one class, and i pass this onto a different class to perform the next calculation with only clicking buttons. So if i click on 'm10py' , whatever i have in the TextArea will be decreased by 0.10. I tried everything but it just doesnt seem to work. It doesnt throw any errors but the total in the TextArea stays still.
My main class where it performs the basic calculation.
public void actionPerformed(ActionEvent e) {
double frontM = 9.50;
double middleM = 7.30;
double backM = 6.70;
double vipM = 12.90;
//double total1 = Double.parseDouble(output.getText());
if (frontR.isSelected() && e.getSource() == calculate) {
double total = Integer.parseInt(frontT.getText()) * frontM;
output.setText(pounds.format(total));
} else if (middleR.isSelected() && e.getSource() == calculate) {
double total = Integer.parseInt(middleT.getText()) * middleM;
String total2 = String.valueOf(total);
output.setText(total2);
} else if (backR.isSelected() && e.getSource() == calculate) {
double total = Integer.parseInt(backT.getText()) * backM;
output.setText(pounds.format(total));
} else if (vipR.isSelected() && e.getSource() == calculate) {
double total = Integer.parseInt(vipT.getText()) * vipM;
output.setText(pounds.format(total));
} else if (e.getSource() == cancel) {
frontT.setText("1");
middleT.setText("1");
backT.setText("1");
vipT.setText("1");
output.setText("");
}
if (e.getSource() == payment) {
Payment paymentJ = new Payment();
paymentJ.output.setText(output.getText());
}
}
Second class which the calculation is passed on to a different textArea. I didnt do it for every button because i couldnt manage to the calculation.. ;
public void actionPerformed(ActionEvent e) {
Main main = new Main();
// double totalR = Double.parseDouble(output.getText());
String cost = main.output.getText();
double cost2 = Double.parseDouble(cost);
double total;
total = cost2;
double m10py = 0.10;
double m20py = 0.20;
double m50py = 0.50;
double m1p = 1.00;
double m2p = 2.00;
double m5p = 5.00;
double m10po = 10.00;
double m20po = 20.00;
if (e.getSource() == m10p) {
total = total - m10py;
String total2 = String.valueOf(total);
output.setText(total2);
}
}
I'm fairly new to this so please dont go have a go at me. I just need to know what is wrong with this. Thanks

One thing I do know is that you've got a serious reference problem going on. For example in your first posted actionPerformed method:
if (e.getSource() == payment) {
Payment paymentJ = new Payment(); // ***** line 1 ****
paymentJ.output.setText(output.getText()); // ***** line 2 ****
}
On line 1 above you create a new Payment object, called paymentJ, and on line 2 you change its state, by calling output.setText(...). I'm guessing that output is some text component, and you're trying to change the text that it displays, but here's the problem -- while paymentJ refers to a Payment object, it's not the Payment object that is being displayed, which is a completely distinct separate object, and changing the state of the non-displayed one created here by trying to change the text it displays, will have no effect on the output text component in the actualy displayed Payment object.
Similarly in your second posted actionPerformed method:
Main main = new Main();
// double totalR = Double.parseDouble(output.getText());
String cost = main.output.getText(); // ***** line 1 ****
double cost2 = Double.parseDouble(cost); // ***** line 2 ****
On line 1 above you create a new Main object, called cost, and on line 2 you query its state, by calling output.getText(). But again the Main instance created here is not the same Main object that is being displayed, and again this means that you have at least two (or more) Main objects, only one of which is being displayed, and the data that your extracting from the one created locally here will not reflect the changes made to the one that's displayed. You can test this by placing a println after you extract the text, for example:
Main main = new Main();
// double totalR = Double.parseDouble(output.getText());
String cost = main.output.getText();
System.out.println("cost is currently: " + cost); // ***** add this ****
double cost2 = Double.parseDouble(cost);
I will bet that you'll see a default value that is held by the text component returned, and not a value that was entered by the user or was displaying in the currently visualized Main GUI.
What to do?
Well for one, you could make the output fields static. That would be a quick and easy solution, but unfortunately it would be quick, easy and very very wrong, since this would break OOPs principles, making your code very difficult to test, enhance and inherit.
Better would be to pass references in where needed, for instance pass a reference to the displayed Payment object into the object that has that first actionPerformed method, and then call the appropriate methods on that object, and likewise pass a valid reference to the displayed Main object into the object whose code is displayed in your lower code snippet. This will allow you to query and modify the states of valid displayed objects. How to do this? I can't tell you specifically how to do this without a better and working code example from you (as per my comments). Generally, you could pass references around using constructor and setter method parameters.
Best would be to make your code more M-V-C or Model-View-Controller like, but this may be overkill for this program and may be beyond your current level of coding at this time.
For more help, for better help, please improve your question.
Based on your new code,
your Payment class should extend JDialog, not JFrame since a GUI should only have one main window
You will want to pass Main into Payment via Payment paymenetJ = new Payment(this);
You will need to change the Payment constructor to accept this: public Payment(Main main)
And inside the constructor use the parameter to set a field: this.main = main;
Then use this main field instead of creating a new Main object.

Related

JAVA seperate class method not incrementing a variable in my main class method

so this is the main code for my text-based game.
import java.util.Scanner;
public class D_M_RPG {
public static void main(String[] args) {
//Creating the class to call on my toolbox
D_M_RPGtoolbox toolbox = new D_M_RPGtoolbox();
//Creating the scanner class for user input
Scanner input = new Scanner(System.in);
//Initiating variables and final variables aswell as arrays
//token variable to validate open spots in an array
int slotCounter = 0;
int inventoryExpander = 11;
//First initiated will be the character creation variables
String hairColor = "";
String eyeColor = "";
String skinColor = "";
String gender = "";
//Initiating the arrays for character inventory slots
String[] weaponSlots = new String[10];
//initiating the arrays for the character creation
String[] hairColorARR = {"black","Green","Yellow","Brown","Blue","Blonde","Grey","White"};
String[] eyeColorARR = {"Green","Brown","Blue","Grey",};
String[] skinColorARR = {"White","brown","Black",};
String[] genderARR = {"Male","Female"};
//Creating the introduction title and introduction
System.out.println("Welcome to, COLD OMEN.");
System.out.println("\nNOVEMBER 12th, 2150: ONTARIO, CANADA");
System.out.println("\nYou hear loud shouts and gun fire all around you but can't pinpoint the location of anything, you feel a bit dazed until someone grabs you and you open your eyes and snap out of it.");
System.out.println("\nUnknown: 'Get up, its time to move out. Take this.'");
System.out.println("\nUnknown hands you a 'M4-A4 RIFLE'");
System.out.println("\nyou manage to catch a small glimpse of him before you get up.");
//Character creation screen
System.out.println();
//ONLY WORKS ONCE WONT INCREMEMENT THE SLOTCOUNTER
toolbox.insert(weaponSlots, slotCounter, inventoryExpander, "M4-A4 RIFLE");
System.out.println("\n" + weaponSlots[0]);
toolbox.insert(weaponSlots, slotCounter, inventoryExpander, "ak47");
System.out.println(weaponSlots[0]);
}
}
so I have this method I made to basically add an "item" to the weaponSlots array (the inventory) but whenever I run it it will add to the first element in the array [0] but it wont incremement the slotcounter which should go up by one every time the method is used so that I dont replace any items in the array It should just add items until its full which is checked using the inventoryExpander variable. at the moment I have it printing the element at 0 and 0 for the array but i have checked 1 aswell and 1 is just null no item added it only just replaces the element at 0. heres the code for the method to increment etc:
public class D_M_RPGtoolbox {
//method for random number generating to be used for crit hits, turns, loot generation etc
public int randomGen(){
int x = (int) (Math.random()*((20-0)+1)+0);
return x;
}
//method for inserting into an array ONLY WORKS ONCE WONT INCREMEMENT THE SLOTCOUNTER FIX
public void insert(String[] a, int b, int d , String c) {
if(b < d) {
a[b] = c;
b++;
}//end of if statement
}//end of method
}
What you are actually performing the ++ operation on in b is a copy of the value in slotCounter.
The variable slotCounter is passed into insert "by-value".
This unlike what you probably imagine, that it is passed "by-reference".
One solution would be to do the slotCounter++ from the call row instead; and another would be to let the toolbox own the slotCounter variable completely.
This question uses the image of passing a copy of document content (by value) where changes to the document would not be seen by the sender; or as a link to a shared document (by reference), where changes could be made to the same page that the sender sees.
Its always going to be zero since you are passing zero and incrementing the local variable b.
Try calling the method as below with post increment ++ to slotCounter and see if it works for you,
toolbox.insert(weaponSlots, slotCounter++, inventoryExpander, "M4-A4 RIFLE");

How to break loop at some point of iteration and check what system printed out?

I am trying to find out how can I check what system printed out at some point of iteration during the while loop statement.
I have this method:
/**
* This method counts how much money user inserted
* If it is not enough to buy chosen cup size it asks user to insert more
* Otherwise it checks if user does not need the change
* and collects money to machine based on cup size price
* This method gets the message from properties file by key identifies
* add.more.money - if not enough money is in machine
* user.paid.change - if user put too much to machine
* user.paid - if user paid the exact amount of money
* #param constantPrice - cup size price
* #return countMoney - how much user put to machine
*/
#Override
public String countMoneyForCupSize(double constantPrice) {
// constant - price depending on cup size
String countMoney = " ";
double sessionMoney = 0;
boolean flag = true;
while(flag) {
if(constantPrice > sessionMoney) {
System.out.println(MessageFormat.format(prop.getProperty("add.more.money"), (constantPrice-sessionMoney)));
double insertedCash;
try {
insertedCash = insertCash();
sessionMoney = sessionMoney + insertedCash;
if(insertedCash == 0) {
System.out.println(MessageFormat.format(prop.getProperty("end.procedure"), sessionMoney));
flag = false;
}
} catch (InvalidCoinException e) {
System.out.println(e.getMessage());
}
}
else {
double change = sessionMoney - constantPrice;
String makeCoffeeText = makeCoffee();
if(change > 0) {
countMoney = MessageFormat.format(prop.getProperty("user.paid.change"), makeCoffeeText, sessionMoney, change);
}
else {
countMoney = MessageFormat.format(prop.getProperty("user.paid"), makeCoffeeText, sessionMoney);
}
collectMoney(constantPrice);
flag = false;
}
}
return countMoney;
}
JUnit:
#org.junit.Rule
public final ProvideSystemProperty property1 = new ProvideSystemProperty("MoreEuro", "You need more: 0.5 euro");
#org.junit.Test
public void testCountMoneyForCupSize() {
System.out.println("---------------- Count Money For Cup Size -----------------");
double largePrice = 1.5;
double mediumPrice = 1;
double smallPrice = 0.75;
try {
when(machineSpy.insertCash()).thenReturn(1.0);
assertEquals(machineSpy.countMoneyForCupSize(largePrice), System.getProperty("MoreEuro"));
} catch (InvalidCoinException e) {
System.out.println(e.getMessage());
}
}
So I want to be clear that If user inserted 1 euro he still needs to insert half a euro more.
1) when(machineSpy.insertCash()).thenReturn(1.0);
Mocking private method invocation called by the tested public method is not necessarily a good thing as you should mock dependency and not the behavior of the object under test. If insertCash() has some specificities that have to be mocked, you should probably move out in another class.
2) About :
how to break loop at some point of iteration and check what system
printed out
Why not just executing a break instruction ?
3) machineSpy.countMoneyForCupSize(largePrice);
So I want to be clear that If user inserted 1 euro. He still need to
insert half euro more
Rather than trying to test the output written in the console that is not really testing the method behavior, I think that you should change the contract of countMoneyForCupSize(double).
In your actual version the method returns a formatted String. It should not.
Logic and rendering tasks are two distinct things.
Mixing both responsibilities violates the Single Responsibility principle (more than one reason to change a class).
Besides, it may prevent from testing the core logic of the method as in your case
Here :
if(change > 0) {
countMoney = MessageFormat.format(prop.getProperty("user.paid.change"), makeCoffeeText, sessionMoney, change);
}
else {
countMoney = MessageFormat.format(prop.getProperty("user.paid"), makeCoffeeText, sessionMoney);
}
You should rather create an instance of a custom class that contains all these data and return it rather than a String.
For example :
....
CountMoney countMoney = null;
...
if(change > 0) {
countMoney = new CountMoney(makeCoffeeText, sessionMoney, change);
}
else {
countMoney = new CountMoney(makeCoffeeText, sessionMoney);
}
...
return countMoney;
In your applicative code that invokes CountMoney countMoneyForCupSize() you could then call a rendered method (located in a rendering class) that performs the rendering, for example : String renderingCountMoney(CountMoney countMoney).
In this way your design would be better (each class and each method has well defined responsibilities) and you can unit test countMoneyForCupSize() without considerations about user text rendering.
You can check directly that insertCash was called multiple times. One way to do this is to to mock multiple calls to insertCash with thenReturn:
when(machineSpy.insertCash()).thenReturn(1.0, 0.5);
After that you can verify that insertCash was called exactly two times:
verify(machineSpy, times(2)).insertCash();
verifyNoMoreInteractions(machineSpy);
Check out this question for other options:
Using Mockito with multiple calls to the same method with the same arguments
If you still want to capture and test the output to System.out then you need to redirect standard output. This was already covered in earlier questions:
Redirect System.out.println
JUnit test for System.out.println()

Simple if-clause not working, can't find the mistake

So I am working on an incremental game at the moment. In case you don't know what this is a short explanation. You click a button to get some kind of money (in my case gold). With enough money you can buy stuff that makes you money without even clicking. With more money you can get better upgrades which makes you even more money and so on.
Now to my problem; I created a class called Upgrade which you can see here:
public class Upgrade {
double baseCost;
double baseIncome;
int count =0;
double cost = baseCost*Math.pow(1.07,count);
double goldPerSecond = baseIncome; //TODO find usefull formula!
public Upgrade(double baseC, double baseIn){
baseCost = baseC;
baseIncome = baseIn;
}
}
The variables should explain themselves.
Now I created some Upgrades via the constructor:
Upgrade waitress = new Upgrade(50 ,2); //Constructor for Waitress
Upgrade seats = new Upgrade(100, 5); //Constructor for More-Seats
Upgrade decoration = new Upgrade(500, 20); //Constructor for Decoration
Upgrade bartender = new Upgrade (1000, 50); //Constructor for Bartender
To buy upgrades I have written the method buyUpgrade which is bound to buttons referring to the upgrades listed above.
public void buyUpgrade(Upgrade U) {
if (goldCount >= U.cost) {
goldCount = goldCount - U.cost;
clickGoldPerSecond++;
U.count++;
} else {
error.setText(getResources().getString(R.string.no_gold));
}
}
And here comes the problem. As the game starts you have 0 gold. That 0 is stored in the variable goldCount. But even though goldCount is I can buy every Upgrade in unlimited amounts. I just cant figure out the problem. Probably it is really simple and afterwards I realize how stupid I was but I just cant figure it out.
Every help is appreciated. Thank you!
The problem is that
double baseCost;
double baseIncome;
int count =0;
double cost = baseCost*Math.pow(1.07,count);
baseCost being the member variable of the class, is intialized to 0.0
SO "cost" set to 0.0 and it never changed after that.
You should move the cost calculation in the constructor.
public Upgrade(double baseC, double baseIn){
baseCost = baseC;
baseIncome = baseIn;
cost = baseCost*Math.pow(1.07,count);
}
public class Upgrade
{
double baseCost;
double baseIncome;
int count =0;
double cost ;
double goldPerSecond;
public Upgrade(double baseC, double baseIn)
{
baseCost = baseC;
cost = baseCost * Math.Pow(1.07,count);
baseIncome = baseIn;
}
}
Your Upgrade class should be similar to what I have created here. If there is a non static filed in the class and you are assigning value to that variable in the way you were doing it will not work.
In your case you also cannot use the static variable as the variable baseCost is passed as constructor parameter and will not be available until you create an instance of upgrade class.
If Condition if(goldCount >= U.cost){} Here the cost will have value of zero only as it would not get updated.
Here is your problem:
int count =0;
double cost = baseCost*Math.pow(1.07,count); // cost is set and will not be updated
Pls note that you update baseCost in your constructor, but before that the default value 0.0 is being used for baseCost * Math.pow(...);. But even if you update that, by having it done in the constructor, still you will not see any price going up, because the cost is not being recalculated at all.
Set the initial value in the constructor (or have baseCost always being added to the cost when accessing the cost).
Make a method which adds one to count and then does Math.pow(...) on cost again.
Now for a much better solution: hence, in this case the attribute cost is useless. Change it into a method:
public double getCost() {
return baseCost*Math.pow(1.07,count);
}
call it (change 2x U.cost --> U.getCost()) and your sky will be blue again, no further change needed where ever.
You are missing getter/setter for cost i guess. Therefore it always return 0.0.
I mean try to create an Upgrade object with the constructor, then print out the cost. No matter what you give in the constructor, the cost for the object always print out "0.0".

Methods in java (grade calculator)

We've been learning about methods in java (using netbeans) in class and I'm still a bit confused about using methods. One homework question basically asks to design a grade calculator using methods by prompting the user for a mark, the max mark possible, the weighting of that test and then producing a final score for that test.
eg. (35/50)*75% = overall mark
However, I am struggling to use methods and I was wondering if someone could point me in the right direction as to why my code below has some errors and doesn't run? I don't want any full answers because I would like to try and do it best on my own and not plagiarise. Any help would be greatly appreciated :)! (Also pls be nice because I am new to programming and I'm not very good)
Thanks!
import java.util.Scanner;
public class gradeCalc
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
scoreCalc();
System.out.print("Your score is" + scoreCalc());
}
public static double scoreCalc (int score1, int maxMark, double weighting, double finalScore)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter mark");
in.hasNextInt();
score1 = in.nextInt();
System.out.print("Enter Max mark");
in.hasNextInt();
maxMark = in.nextInt();
System.out.print("Enter weighting as a decimal (eg. 75% = 0.75)");
in.hasNextInt();
weighting = in.nextInt();
finalScore = (score1/maxMark)* weighting;
return finalScore;
}
}
You are calling your method scoreCalc() without passing the parameters you defined.
When you are calling it, it was defined as having 3 parameters.
scoreCalc(7, 10, 3.0, 8.0);
Also, when creating a class, start it with upper case, GradeCalc
As you can see scoreCalc method needs a set of parameters, but you call it without parameters.
The second: there is no need in Scanner in = new Scanner(System.in); into your main(String[] args) method. You are calling it into scoreCalc method.
Third: you are calling scoreCalc twice. The first call is before System.out.println, the second is into System.out.println. And your application will ask user twice to enter values.
store result value in a variable and show it later:
double result = scoreCalc(.... required params .....);
System.out.println("Your score is: " + result);
To start :
1) Follow coding conventions. (Class name should start with a capital letter).
2) In your context, you don't need Scanner in = new Scanner(System.in); in main() because you are not using it.
3) You are a calling the method scoreCalc() without parameters. Whereas, the method needs to be called with parameters.
4) A method,is a module. It as block of code which increases re-usability. So I suggest that accept the values from user in main() method and then pass them to the method for calculation.
A couple of things spring to mind:
You execute scoreCalc() twice. Probably you want to execute it once and save the result in a double variable like: double score = scoreCalc().
Speaking of scoreCalc(): Your definition takes 4 parameters that your don't have as input for that method. You should remove those from your method definition, and instead add score1, maxMark, weighting and finalScorevariable declarations in the method-body.
In your main function, you declare and instantiate a Scanner object you don't use.
Be careful with arithmetic that mixes int and double.
Some mistakes/errors to point out are:-
1) You do not need this statement Scanner in = new Scanner(System.in); in your main() , as you are not taking input from user through that function.
2) Your function scoreCalc (int score1, int maxMark, double weighting, double finalScore) takes parameters, for example its call should look like scoreCalc(15, 50, 1.5, 2.7), but you are calling it as scoreCalc(), that is without paramters from main().
Edit:- There is one more serious flaw in your program, which might work , but is not good coding. I wont provide code for it , and will leave implementation to you. Take input from user in the main() (using scanner) , assign the result to a temp variable there, and then pass that variable as parameter to the function scoreCalc()
//pseudocode in main()
Scanner in = new Scanner(System.in);
int score= in.nextInt();
.
.
.
scoreCalc(score,...);
Or you can make your scoreCalc function without parameters, and take user input in it (like present), and finally return just the result to main().
Both approaches seem appropriate and you are free to choose :)
As opposed to other answers I will start with one other thing.
You forgot about the most important method - and that is the Constructor.
You have to create a grade calculator, so you create a class(type) that represents objects of grade calculators. Using the Java convention this class should be named GradeCalculator, don't use abbreviations like Calc so that the name is not ambiguous.
So back to the constructor - You have not created your Calculator object. It may not be needed and you may achieve your goal not using it, but it's not a good practice.
So use this method as well - this way, you'll create actual Calculator object.
It can be achieved like that:
public static void main(String[] args)
{
GradeCalculator myCalculator = new GradeCalculator();
}
And now you can imagine you have your calculator in front of you. Whan can you do with it?
Getting a mark would be a good start - so, what you can do is:
myCalculator.getMark()
Now you'll have to define an method getMark():
private void getMark() { }
In which you would prompt the user for the input.
You can also do:
myCalculator.getMaxMark() { }
and that way get max mark (after defining a method).
The same way you can call method myCalculator.getWeighting(), myCalculator.calculateFinalResult(), myCalculator.printResult().
This way you'll have actual object with the following mehtods (things that it can do):
public GradeCalculator() { } //constructor
private void getMark() { } //prompts user for mark
private void getMaxMark() { } //prompts user for max mark
private void getWeighting() { } //prompts user for weighting factor
private void calculateFinalResult() // calculates the final result
private void printResult() // prints the result.
And that I would call creating a calculator using methods - and that I would grade highly.
Try to think of the classes you are creating as a real objects and create methods representing the behaviour that objects really have. The sooner you'll start to do that the better for you.
Writing whole code in one method is not a good practice and in bigger applications can lead to various problems. So even when doing small projects try to do them using best practices, so that you don't develop bad habbits.
Edit:
So that your whole program can look like this:
import java.util.Scanner;
public class GradeCalculator
{
//here you define instance fields. Those will be visible in all of your classes methods.
private Scanner userInput; //this is the userInput the calculator keypad if you will.
private int mark; //this is the mark the user will enter.
private int maxMark; //this is the mark the user will enter.
private int weightingFactor; //this is the weighting factor the user will enter.
private int result; //this is the result that will be calculated.
public static void main(final String args[])
{
Scanner userInput = new Scanner(System.in); //create the input(keypad).
GradeCalculator calculator = new GradeCalculator(userInput); //create the calculator providing it with an input(keypad)
calculator.getMark();
calculator.getMaxMark();
calculator.getWeightingFactor();
calculator.printResult();
}
private GradeCalculator(final Scanner userInput)
{
this.userInput = userInput; //from now the provided userInput will be this calculators userInput. 'this' means that it's this specific calculators field (defined above). Some other calculator may have some other input.
}
private void getMark() { } //here some work for you to do.
private void getMaxMark() { } //here some work for you to do.
private void getWeightingFactor() { } //here some work for you to do.
private void printResult() { } //here some work for you to do.
}
Please mind the fact that after constructing the Calculator object you don't have to use methods that are static.

Update value in Java ArrayList

I wasn't too sure what to title this question, apologies in advance. I currently have a value of say 50 stored in the BidderArray. I want to be able to increase that 50 by any given number entered into a text field.
So say I want to add 10 to the existing 50, it will return 60. Currently when I add the 10 the 50 is replaced by 10 instead of adding the two together. I understand why my code is doing this but haven't been able to find any tutorials or hints on what I should be doing instead.
Here is the code:
package abc;
import java.awt.*;
public class Funds extends javax.swing.JFrame {
int i = 0;
Bidder bidbal = new Bidder();
/** Creates new form Funds */
public Funds() {
initComponents();
}
private void addActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
int f = 0;
boolean validEntries = true;
try{
f = Integer.parseInt(amount.getText());
Bidder.BidderArray.get(i).setRegFee(f);
} catch (Exception error) {
validEntries = false;
amount.setBackground(Color.red);
}
if (validEntries) {
Bidder.exportBidder();
Home home = new Home();
home.setVisible(true);
this.dispose();
}
}
}
You aren't actually adding anything
Bidder.BidderArray.get(i).setRegFee(f);
is apparently just setting something to f, you have to get the current value, add to it, and then put it back. But this is just a guess as we don't have enough actual code to know what you are doing wrong.
You have to get the current fee, add the value, and then set the fee:
f = Integer.parseInt(amount.getText());
Bidder.BidderArray.get(i).setRegFee( f + Bidder.BidderArray.get(i).getRegFee() );
Or you could add a new method the Bidder class that adds to the fee:
class Bidder
{
//...
public void addToRegFee( int amount )
{
this.regFee += amount;
}
}
f = Integer.parseInt(amount.getText());
Bidder.BidderArray.get(i).addToRegFee( f );
f = Integer.parseInt(amount.getText());
Bidder.BidderArray.get(i).setRegFee(f);
Here, it seems like you're getting the user's input (f), and just set the array's element value to it. What it sounds like you want to do is to take that input (f), and the array's element existing value, combine (read: add) them, before setting the element's value to that new combined value.
In pseudo-code, this is what you're doing:
f := get user's input
setValue(f)
What you need to do:
f := get user's input
g := get current value
setValue(f + g)
You must add it to your old value:
//Add old to new (Unless you have a different method set for get like
//getRegFee (Not sure how bidder is implemented))
Bidder.BidderArray.get(i).setRegFee(Bidder.BidderArray.get(i) + f);

Categories