[英]How to compare two consective numbers of an array in java
I am trying to compare two consecutive numbers of an array and print the largest one in every iteration.我正在尝试比较一个数组的两个连续数字并在每次迭代中打印最大的一个。 I have written below code but its giving unexpected responses.
我写了下面的代码,但它给出了意想不到的响应。 Can somebody please check and help me understand the mistake.
有人可以检查并帮助我理解错误。
PS: I just started learning java. PS:我刚开始学习java。
public class Test {
public static void main(String [] args){
int[] list = {6,0,4,2,9};
int current;
for(int j=0; j<list.length-1; j++){
if(list[j]>list[j+1]){
current = j;
}else{
current = j+1;
}
System.out.print(current + " ");
}
}
}
Expected response: 6 4 4 9
Actual response: 0 2 2 4
Ok so your code is just returning j
which here is used as the number in youy for
loop.好的,所以您的代码只是返回
j
,这里用作 youy for
循环中的数字。
In your if
you're using j
as an index to get the value in list
matching that index; if
您使用j
作为索引来获取与该索引匹配的list
中的值; but in the rest of your for
loop you're setting current
to the value of j
and not the value of list
at the index j
.但是在
for
循环的 rest 中,您将current
设置为j
的值,而不是索引j
处的list
的值。
What you'll want to print is the value of list[j]
and not j
.您要打印的是
list[j]
而不是j
的值。
In fact, if you look closely [0 2 2 4]
are the indexes of [6 4 4 9]
事实上,如果你仔细观察
[0 2 2 4]
是[6 4 4 9]
的索引
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.