英文:
Why does this piece of code say variable j might not have been initialized?? It is getting initialized inside the loop
问题
class Searching {
static int search(int arr[], int N, int X) {
int j;
for (int i = 0; i < N; i++) {
if (arr[i] == X) {
j = i;
break;
}
}
return j;
}
}
我在循环内部初始化了 j。所以为什么编译器在达到返回语句时会报告 j 未初始化。我作为一个编程新手无法理解。请帮助我。
英文:
class Searching{
static int search(int arr[], int N, int X)
{
int j;
for(int i = 0; i<N; i++){
if(arr[i] == X){
j = i;
break;
}
}
return j;
}
}
I have initialized j inside the loop. So why does the compiler say j is not initialized when it reaches the return statement. I am not able to understand as I am new to coding.. Please help me
答案1
得分: 1
在Java中,for
循环是前测试循环:测试条件(i<N
)在循环体之前执行。因此,如果N
小于或等于i
的初始值(0
),循环将永远不会执行,且j
将永远不会被初始化。
但还有另一个评论者忽略的问题:即使循环执行,如果要搜索的元素不存在于数组中,j
也永远不会被初始化。
另外,与其将N
作为参数传递,你应该能够直接从数组中获取它(虽然我现在无法记起如何做到这一点)。
英文:
In Java, for
loops are pre-test loops: the test (i<N
) is executed before the loop body. So if N
is less than or equal to the initial value of i
(0
), then the loop wil never execute and j
will never be initialised.
But there’s another issue that the commentators missed: even if the loop executes, if the element being searched for does not exist in the array, j
will never be initialised.
On another note, instead of passing N
as a parameter, you should be able to get it directly from the array (though I can’t remember how to do it right now).
答案2
得分: 1
这是因为参数 N
可能等于 0,所以循环不一定会执行,或者数组不包含 x
,因此变量 j
不会被初始化。
我建议你像这样初始化:int j = -1;
,然后如果方法返回 -1
,你就会知道出了问题(N = 0
或数组不包含 x
)。
英文:
This is happens because the parameter N
can be equals to 0, so the loop isn't must running, or array isn't contains x
, so the variable j
will not initialize.
I suggest you to initialize like int j = -1;
, and than if the method returns -1
you will know that something go wrong (N = 0
or array isn't contains x
).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论