Java - add value to it to a variable from another class -


my problem how add value variable class, example:

private int balance; 

then later in methods in same class, add values balance no problem using:

balance += 50; 

but when go class, , type object setter balance:

myobject.setbalance(50); 

but problem strikes here, when go first class , return balance there, nothing (or old value of balance) in other words, new value of balance not being added. ideas why? i've been stuck @ point last couple of hours

here's code:

public class zoo  {     private int balance;      public void setbalance(int balance)     {         this.balance = balance;     }      public int getbalance()     {         return this.balance;     } }  second class:  public class randomevents {     private zoo zoobalance = new zoo();      public void calleventsix()     {         system.out.println("a local group has raised money zoo");         system.out.println("would accept money? (y) or (n)");         scanner readereventthree = new scanner(system.in);         string readertwo = readereventthree.next();         if ( readertwo.equals("y") )          {             zoobalance.setbalance(166);             system.out.println("you have accepted gift");             system.out.println("your new balance " + zoobalance.getbalance());         } else if ( readertwo.equals("n") )         {             system.out.println("you have refused gift");         }     } } 

in case

replace line:

zoobalance.setbalance(166); 

with:

zoobalance.setbalance(zoobalance.getbalance() + 166); sytem.out.println(zoobalance.getbalance()); // 166 

you need make setter class. assuming name of class testclass.

class testclass {     private int balance = 50; }; public int getbalance() {     return this.balance; }; public void setbalance(int newbalance) {     this.balance = newbalance; }; 

and in class:

testclass test = new testclass(); test.setbalance(test.getbalance() + 50); system.out.println(test.getbalance);// 100 

Comments

Popular posts from this blog

c# - Operator '==' incompatible with operand types 'Guid' and 'Guid' using DynamicExpression.ParseLambda<T, bool> -