当我在Java循环时获得无限
我想编写一个在2D数组中循环的代码,主要方法是FindVal,该方法获得了2D数组和一个值并返回true如果值在数组中,我使用二进制搜索代码来循环循环。数组和另一种方法在2D数组中排成一行时,问题是当我运行测试器时,它不会打开终端窗口,看来我的循环是无限的,我的代码是以下内容,以下是
public static int linearSearch(int [] arr, int num)
{
int pos=0;
while ((arr[pos]<num)&&(pos<arr.length-1))
pos++;
if(arr[pos]==num){return pos;}
else {return -1;}
}
public static boolean findVal(int [][] m, int val)
{
int n=m.length;
int j=m.length-1, i=0;
while (i<=j)
{
if(val == m[i][j]){return true;}
else if(val > m[i][j] ){
if(linearSearch(m[i],val) !=-1){return true;}
}
else{
i++;
}
}
return false;
}
有人告诉我什么我做错了吗? 注意:我不能使用嵌套环,既不是通过n*n进行循环的n*n。
I want to write a code which loops in a 2d array, the main method is findVal which gets a 2d array and a value and return true if the value is in the array, I used a binary search code to loop through a single row of the array and another method which goes down in rows in the 2d array, the problem is when I run a tester it doen't open the terminal window and it looks like my loop is infinite, my code is the following
public static int linearSearch(int [] arr, int num)
{
int pos=0;
while ((arr[pos]<num)&&(pos<arr.length-1))
pos++;
if(arr[pos]==num){return pos;}
else {return -1;}
}
public static boolean findVal(int [][] m, int val)
{
int n=m.length;
int j=m.length-1, i=0;
while (i<=j)
{
if(val == m[i][j]){return true;}
else if(val > m[i][j] ){
if(linearSearch(m[i],val) !=-1){return true;}
}
else{
i++;
}
}
return false;
}
can someone tell me what I'm doing wrong?
Note: I can't use nested loops neither run through n*n in a for loop.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的
主体具有 -
else
- - else 结构三个分支。第一个使用返回
语句退出该方法,因此不会导致无限循环。第三个增量i
,因此最终应导致循环结束。这是第二个问题。它包含条件返回
语句。但是,如果未满足这种情况,则循环主体 nothing 。这意味着循环条件不会改变,并且每次都选择相同的分支。Your
while
body has anif
-else if
-else
structure with three branches. The first uses areturn
statement to exit the method, so that won't cause an infinite loop. The third incrementsi
so that should eventually cause the loop to end. It's the second one that's the issue. It contains a conditionalreturn
statement. However, if that condition is not met, the loop body does nothing. That means that the loop condition won't change, and the same branch is chosen every time.您的其他条件是否导致循环无限。
如果
linearsearch(m [i],val)
返回-1。您并没有增加I或J,而I或J则导致I和J的相同值在同时循环中一次又一次地评估。尝试执行i ++,以防
linearsearch(m [i],val)== -1
的值,该值将解决无限循环的问题Your else if condition is causing the loop to go infinite.
In case -1 is returned from the
linearSearch(m[i],val)
. You are not increasing i or j which in turn is causing the same values of i and j to be evaluated again and again in the while loop.Try to do a i++ in case the value from
linearSearch(m[i],val) == -1
that will fix the issue of infinite loop