Right now, I'm learning all about class, constructors and instances. I've made a small bit of code in java and I'm stuck with this particular code.
***MY CODE OUTPUT IS SUPPOSE TO BE LIKE THIS:
OUTPUT
Enter amount:500
Do you want to enter amount again?(y/n):y
Enter amount:45
Do you want to enter amount again?(y/n):n
TOTAL:545
***BUT INSTEAD MY OUTPUT IS LIKE THIS:
OUTPUT
Enter amount:500
Do you want to enter amount again?(y/n):y
Enter amount:45
Do you want to enter amount again?(y/n):n
TOTAL:45
***It is not adding the amount that I enter throughout the loop and instead, it is giving me the very last amount that I input.
Here is the first code:
public class Test {
private double money;
public Test(){
}
public void addPoints(double money1){
money += money1;
}
public int getMoney(){
return money;
}
}
and the second code is here:
import java.util.Scanner;
public class testBody {
public static void main(String[]args){
double cashMoney;
String response = "";
Scanner hold = new Scanner(System.in);
do{
System.out.print("Enter amount:");
cashMoney = hold.nextDouble();
Test cashPlus = new Test();
cashPlus.addPoints(cashMoney);
System.out.print("Do you want to enter amount again?(y/n):");
response = hold.next();
if(response.equalsIgnoreCase("n")){
System.out.print("TOTAL: " + cashPlus.getMoney());
}
}while(response.equalsIgnoreCase("y"));
}
}
You should create the
Test
instance before the loop instead of in each iteration.Each time you create a new Test instance,
cashMoney
is initialized to 0 (since each instance has its own value of that member). When you finally printcashPlus.getMoney()
, you print the value of the last instance you created, to which you only added the final amount you entered.