在Java中为变量分配新值

时间:2018-08-31 14:58:10

标签: java variables

我是Java新手,对变量有疑问。这是一个例子。

int hello = 6;
int goodbye = 7;
int combined = hello + goodbye;

    System.out.println(combined);
    hello = 10;
    System.out.println(combined);

当我重新分配问候,并为其指定10而不是6的值时,我第二次打印合并,它仍然说合并等于13,而不是控制台中的17。您如何解决?谢谢!

5 个答案:

答案 0 :(得分:2)

您需要重新计算query,因为将值重新分配给{ "sort": [ { "_geo_distance": { "location": { "lat": 24.71532, "lon": 46.66479 }, "order": "asc", "unit": "km", "distance_type": "plane" } } ], "query": { "bool": { "must": [ { "term": { "type": "user" } } ], "filter": { "geo_distance": { "distance": "1000km", "location": { "lat": 24.71532, "lon": 46.66479 } } } } } } 并不意味着ubuntu也将得到更新。 ubuntu的值是使用#!/usr/local/bin/ruby # Get the latest nurax master # Make a branch with today's date and update hyrax # Push and deploy that branch today = Time.now.strftime('%Y-%m-%e-%H-%M') `cd /home/ubuntu/nurax; git checkout master; git pull; git checkout -b "#{today}"` `cd /home/ubuntu/nurax; bundle update hyrax` `cd /home/ubuntu/nurax; git commit -a -m 'Daily update for "#{today}"'; git push --set-upstream origin #{today}` `cd /home/ubuntu/nurax; BRANCH_NAME="#{today}" cap nurax-dev deploy` `cd /home/ubuntu/nurax; git checkout master; git branch -d "#{today}"; git push origin --delete "#{today}"` 的当前值(当时)计算得出的值。

combined

答案 1 :(得分:1)

您正在传递int类型,该类型将按值执行所有操作 。这意味着它将为combinedhello值加在一起的goodbye分配副本

它们是完全独立且没有连接的。

额外阅读

答案 2 :(得分:1)

combined不会因为确定它的变量之一而改变。您每次都需要手动更新combined

对于这种简单情况,最简单的方法就是再次写入hello + goodbye,如@lealceldeiro的答案所示。

但是对于更复杂的代码,与其将相同的代码复制到多个位置,不如将其包装在一个函数中会更好:

public int doSomeMath(int x, int y) {
    return x + y; //Pretend this is some complicated equation 
}

然后,当您需要多次进行数学运算时,可以使用以下函数:

int hello = 6;
int goodbye = 7;

// Prints 13
System.out.println(doSomeMath(hello, goodbye));

goodbye = 10;

//Prints 17 
System.out.println(doSomeMath(hello, goodbye));

答案 3 :(得分:1)

您正在打印变量组合而不是变量hello。要查看合并后的更改,您需要使用表达式进行重新计算。

int hello = 6; // hello has 6
int goodbye = 7; // goodbye has 7
int combined = hello + goodbye; // combined = 6 (value of hello) + 7 (value of goodbye) = 13

System.out.println(combined); //hence this prints value 13 which is assigned to combined
hello = 10; // changing the value of hello to 10.
System.out.println(combined); // since there is no change in combined value you will get 13 itself.

//In order to change the value of combined you need to assign the value again. In this case you need to re-evaluate combined.
combined = hello + goodbye; //Since now value of hello is 10.Expression will be 10 + 7 = 17
System.out.println(combined);//Output will be 17.

答案 4 :(得分:0)

您可以将int combined = hello + goodbye;(或一般意义上的变量)视为整数值的占位符。因此,在执行combined时,您要用存储在占位符hellogoodbye中的值的总和填充名为hello = 10;的整数占位符。以后执行hello时,只将10放在了名为combined的占位符中。这根本不会影响int combined = hello + goodbye;占位符。

因此恢复:写hello + goodbye时并不是说合并是操作shares,而是操作执行时的结果。