赶上为什么它起作用。变量biggest
用一个计数器初始化,该计数器从数组列表的索引0开始,其值为3
。但是,在while循环中进行比较时,如果3大于3(如果计数器未上升),则它会比较3。 counter
上升,但是初始化的“最大”变量保持不变。为什么?
public static int greatest(ArrayList<Integer> list) {
System.out.println(list);
int counter = 0;
int biggest = list.get(counter); // biggest starts at index 0 - value 3 // this counter seems to go up but the "biggest"
// value remains the same when the counter below goes up.
while (counter< list.size() ){// goes to while loop
if ( list.get(counter)>biggest){
biggest=list.get(counter);
}
counter++;
}
System.out.println(biggest);
System.out.print(counter);
return biggest;
}
public static void main(String[] args) {
ArrayList<Integer> lista = new ArrayList<Integer>();
lista.add(3);
lista.add(2);
lista.add(71);
lista.add(2);
System.out.println("The greatest number is: " + greatest(lista));
}
答案 0 :(得分:1)
仅当循环中的当前值大于当前存储在最大值中的值时,最大变量才会更改。
list.get(counter)>biggest
这就是为什么您看不到它总是在变化的原因。
我添加了一些照片以更好地展示这个概念,希望您可以使用它来更好地理解。
public static int greatest(ArrayList<Integer> list) {
System.out.println(list);
int counter = 0;
int biggest = list.get(counter); // biggest starts at index 0 - value 3 // this counter seems to go up but the "biggest"
// value remains the same when the counter below goes up.
while (counter< list.size() ){// goes to while loop
System.out.println("Current biggest value: " + biggest);
System.out.println("Current iteration value: " + list.get(counter));
if ( list.get(counter)>biggest){
System.out.println("Current value is bigger than biggest! Changing biggest value...");
biggest=list.get(counter);
}
counter++;
}
System.out.println(biggest);
System.out.print(counter);
return biggest;
}
public static void main(String[] args) {
ArrayList<Integer> lista = new ArrayList<Integer>();
lista.add(3);
lista.add(2);
lista.add(71);
lista.add(2);
System.out.println("The greatest number is: " + greatest(lista));
}
作为奖励,我还想分享另一个可以简化的for循环完成的版本。
请注意,此处如何将max的值设置为整数可以有意获得的最小可能值。
这样做,我们可以确定它肯定比ArrayList中找到的任何其他值都要低。
这里是例子:
public int getMax(ArrayList<Integer> list){
int max = Integer.MIN_VALUE;
for(int i=0; i<list.size(); i++){
if(list.get(i) > max){
max = list.get(i);
}
}
return max;
}