简体   繁体   English

如何多次调用方法来更改变量?

[英]How to call a method multiple times to change a variable?

I am trying to call an accelerate method on a speed variable that adds 5 to the speed variable each time it is called. 我试图在speed变量上调用accelerate方法,每次将其加5到speed变量上。 I'm able to do it once in the constructor: 我能够在构造函数中执行一次:

public int getAccelerate() {
    accelerate = (speed + 5);
    return accelerate;
}

and display it using 并使用显示

System.out.println(car1.getAccelerate());

but that only works once, which displays 105 if the speed variable is 100. 但这只能运行一次,如果速度变量为100,则显示105。

My question is: how do I update the speed variable each time the accelerate method is called to reflect the new speed value? 我的问题是:每次调用accelerate方法以反映新的速度值时,如何更新速度变量?

Calling it 5 times gives me the output 叫它5次给我输出

105 105
105 105
105 105
105 105
105 105

where I am trying to get the output 我试图获得输出的地方

105 105
110 110
115 115
120 120
125 125

by calling the same method 5 times. 通过相同的方法调用5次。

Think about what is happening. 想想正在发生什么。 Your method takes speed , adds 5 to it, and puts that value in the variable accelerate . 你的方法需要speed ,增加了5到它,并把该值在变量accelerate Then it returns accelerate . 然后它返回accelerate So every time, you change accelerate based on speed , but you never change speed ! 因此,每次您都根据speed更改accelerate ,但您从不更改speed So for example, if speed is 100 , the first call will return 100 + 5 , the second call will return 100 + 5 , and so on. 因此,例如,如果speed100 ,则第一个调用将返回100 + 5 ,第二个调用将返回100 + 5 ,依此类推。

If you want this to work properly, change accelerate each time: 如果您希望此操作正常,请每次更改加速:

public int getAccelerate()
{
    accelerate = (accelerate + 5);
    return accelerate;
}

Or you could change speed each time: 或者您可以每次更改速度:

public int getAccelerate()
{
    speed = (speed + 5);
    return speed;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM