我无法更改变量Java的值?
我使用else if中首先接受的值调用此方法,else if-使用更改的值再次调用此方法。然后在if-中接受这些值,我想更改sum2的值,它在PrintLine中给出正确答案,但返回初始值-0??非常感谢-少年我无法更改变量Java的值?,java,variables,parameter-passing,Java,Variables,Parameter Passing,我使用else if中首先接受的值调用此方法,else if-使用更改的值再次调用此方法。然后在if-中接受这些值,我想更改sum2的值,它在PrintLine中给出正确答案,但返回初始值-0??非常感谢-少年 private long remove(int k, long summ) { long sum2 = 0; Number smallest = heap.peek(); if (smallest.occurancy &g
private long remove(int k, long summ) {
long sum2 = 0;
Number smallest = heap.peek();
if (smallest.occurancy >= k) {
int number = smallest.number;
sum2 = (long) summ + (number*k); // ????????????????
System.out.println(sum2 + " sum2"); // THIS IS CORRECT ???????????
int newOccurancy = smallest.occurancy-k;
heap.poll();
heap.add(new Number(number, newOccurancy));
}
else if (smallest.occurancy < k) {
int occurancysLeftInSmallest = smallest.occurancy;
summ+= smallest.number * occurancysLeftInSmallest;
System.out.println(summ);
heap.poll();
k-=occurancysLeftInSmallest;
remove(k, summ);
}
return sum2; // BUT RETURNS 0 ???????????
}
private long remove(int k,long summ){
长sum2=0;
Number最小=heap.peek();
如果(最小发生率>=k){
整数=最小的整数;
sum2=(长)总和+(数字*k);/????????????????
System.out.println(sum2+“sum2”);//这是正确的吗???????????
int newOccurancy=最小的.occurancy-k;
heap.poll();
添加(新编号(编号,新发生率));
}
否则如果(最小发生率
返回sum2,它是函数的局部变量,仅在函数结束时有效。如果您将sum2放入类中,它将起作用。@Mike'Pomax'Kamermans summ是一个参数您的问题是在else
条件中不使用recursiveremove
调用的返回值,sum2永远不会被修改。让我们进行一些调试:在第一个If
块中更新sum2
,那么:这真的起作用了吗?什么是最小。发生率和k
?当然,添加了return-remove(x,x)并将其放在if开头。非常感谢!事情根本不是这样的。带有返回值的return
的要点是从方法中获取数据。