Java 如何用while循环替换for循环方法
我是编程新手,并尝试学习java。我试图用while循环替换此方法中的for循环。有人能帮我怎么做吗?因为我写的代码不正确 这是原创的Java 如何用while循环替换for循环方法,java,arrays,for-loop,if-statement,while-loop,Java,Arrays,For Loop,If Statement,While Loop,我是编程新手,并尝试学习java。我试图用while循环替换此方法中的for循环。有人能帮我怎么做吗?因为我写的代码不正确 这是原创的 public static int doSomething(int [] a, int x) { for (int i = 0; i < a.length; ++i) if (a[i]<=x) return i; return -1; } 公共静态int doSomething(int[]a,int x){ 对于(
public static int doSomething(int [] a, int x) {
for (int i = 0; i < a.length; ++i)
if (a[i]<=x) return i;
return -1;
}
公共静态int doSomething(int[]a,int x){
对于(int i=0;i if(a[i]仅此部分:if(a[i]在if
和while
之后使用括号。这是一种很好的做法
public static int doSomething(int [] a, int x) {
i=0;
while (i < a.length){
if(a[i] <=x){
return i;
}
i++;
}
return -1;
}
公共静态int doSomething(int[]a,int x){
i=0;
while(i if(a[i]您的i++是不可访问的,因为它位于return语句后面。您可能希望将其移出if情况
i=0;
while (i < a.length){
if(a[i] <=x){
return i;
i++; //from here
}
i++ //to here
/* this block is also not what you want, this block would be exectued every time
a[i] <=x would be false, so probably most of the time.
else{
return -1; //you should move this frome here
}
*/
}
return i; //to here, and remove the return i; . If the while loop is done and hasen't returned
//with your first return statement, then it shouldn't return with i here either.
//It should return with the -1 from above
}
i=0;
while(i if(a[i]return语句之后的任何内容都是死代码
i=0;
while (i < a.length){
if(a[i] <= x) {
return i;
i++; // This is your mistake
} else {
return -1;
}
}
return i;
i=0;
while(i 如果[i]i++
无法访问,因为您将它放在同一范围内的return
语句下面。您混合了好代码和错误代码。此外,此示例甚至不会编译(缺少分号)。我建议保持格式可读性。
i=0;
while (i < a.length){
if(a[i] <=x){
return i;
i++; //from here
}
i++ //to here
/* this block is also not what you want, this block would be exectued every time
a[i] <=x would be false, so probably most of the time.
else{
return -1; //you should move this frome here
}
*/
}
return i; //to here, and remove the return i; . If the while loop is done and hasen't returned
//with your first return statement, then it shouldn't return with i here either.
//It should return with the -1 from above
}
i=0;
while (i < a.length){
if(a[i] <= x) {
return i;
i++; // This is your mistake
} else {
return -1;
}
}
return i;
i=0;
while (i < a.length){
if(a[i] <= x) {
return i;
}
i++;
}
return -1;