0

我的问题是如何将值添加到另一个类的变量中,例如:

private int balance;

然后稍后在同一类的方法中,我使用以下方法将值添加到余额中没有问题:

balance += 50;

但是当我去另一个班级时,输入对象然后是余额的设置器:

myObject.setBalance(50);

但是问题出现在这里,当我去头等舱并从那里归还余额时,我什么也没得到(或余额的旧值),换句话说,余额的新值没有被添加。任何想法为什么?在过去的几个小时里,我一直被困在这一点上

这是我的代码:

public class Zoo 
{
    private int balance;

    public void setBalance(int balance)
    {
        this.balance = balance;
    }

    public int getBalance()
    {
        return this.balance;
    }
}

MY SECOND CLASS:

public class RandomEvents
{
    private Zoo ZooBalance = new Zoo();

    public void callEventSix()
    {
        System.out.println("A local group has raised money to your Zoo");
        System.out.println("Would you like to accept the 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 the gift");
            System.out.println("Your new balance is " + ZooBalance.getBalance());
        } else if ( readerTwo.equals("n") )
        {
            System.out.println("You have refused the gift");
        }
    }
}
4

3 回答 3

5

在你的情况下

替换这一行:

ZooBalance.setBalance(166);

和:

ZooBalance.setBalance(ZooBalance.getBalance() + 166);
Sytem.out.println(ZooBalance.getBalance()); // 166

您需要setter为该课程制作一个。假设类的名称是TestClass.

class TestClass {
    private int balance = 50;
};
public int getBalance() {
    return this.balance;
};
public void setBalance(int newBalance) {
    this.balance = newBalance;
};

然后在另一个班级:

TestClass test = new TestClass();
test.setBalance(test.getBalance() + 50);
System.out.println(test.getBalance);// 100
于 2013-05-10T14:11:46.700 回答
2

我很确定添加50一个值和将一个值设置为50.

myObject.setBalance(50);不会添加50,它会将值更改为50。要添加 50,您必须执行以下操作myObject.setBalance(myObject.getBalance() + 50);

于 2013-05-10T14:12:30.650 回答
1

通常有两种方法。

第一的。使用gettersetter

Zoo zoo = new Zoo();
zoo.setBalance(zoo.getBalance() + 50);

第二。添加adder方法:

public void addToBalance(int addend) {
    balance += addend;
}

Zoo zoo = new Zoo();
zoo.addToBalance(50);
于 2013-05-10T14:50:39.697 回答