在Java中为变量分配新值 [英] Assigning New Values to Variables in Java
问题描述
我是Java新手,对变量有疑问.这是一个例子.
I am new to Java, and have a question about variables. Here is an example.
int hello = 6;
int goodbye = 7;
int combined = hello + goodbye;
System.out.println(combined);
hello = 10;
System.out.println(combined);
当我重新分配问候,并为其指定10而不是6的值时,我第二次打印合并,它仍说合并等于13,而不是控制台中的17.您如何解决?谢谢!
When I reassign hello, and give it the value of 10 instead of six, and I print combined the second time, it still says combined is equal to 13, not 17 in the console. How do you fix that? Thank You!
推荐答案
combined
不会改变,只是因为确定它的变量之一发生了变化.您每次都需要手动更新 combined
.
combined
won't changed just because one of the variables determining it changed. You'll need to manually update combined
every time.
对于这种简单的情况,最简单的方法就是再次编写 hello +再见
,如@lealceldeiro的答案所示.
For this simple case, the simplest way would just be to write hello + goodbye
again as shown in @lealceldeiro's answer.
但是对于更复杂的代码,与其将相同的代码复制到多个位置,不如将其包装在一个函数中会更好:
For more complicated bits of code though, instead of duplicating the same code multiple places, it would be better to wrap that code in a function:
public int doSomeMath(int x, int y) {
return x + y; //Pretend this is some complicated equation
}
然后,当您需要多次进行数学运算时,可以使用以下函数:
Then, when you need to do the math later multiple times, you use the function:
int hello = 6;
int goodbye = 7;
// Prints 13
System.out.println(doSomeMath(hello, goodbye));
goodbye = 10;
//Prints 17
System.out.println(doSomeMath(hello, goodbye));
这篇关于在Java中为变量分配新值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!