所以到目前为止,我得到了以下代码:
int secondLargest = list.get(0); int largest = list.get(0); for (int i = 0; i < list.size(); i++) { if(list.get(i) > largest) { secondLargest = largest; largest = list.get(i); if(list.get(i) > secondLargest && list.get(i) != largest) { secondLargest = list.get(i); } } } System.out.print("Second biggest number "); return secondLargest;
问题是当我使用此代码时(列表为:)
list2.add(1); list2.add(2); list2.add(10); list2.add(9); list2.add(8); list2.add(7);
第二个最高数字的“搜索”停止于2,因为10是最高数字。我该如何解决?
将第二个if condition条件放在第一个条件条件之外。
if condition
因为second largest小于,largest所以您永远不会在if检查最大值的块中找到它。
second largest
largest
if
int secondLargest = (int) list.get(0); int largest = list.get(0); for (int i = 1; i < list.size(); i++) { if(list.get(i) > largest) { secondLargest = largest; largest = list.get(i); } if(list.get(i) > secondLargest && list.get(i) != largest) { secondLargest = list.get(i); } } System.out.print("Second biggest number "); return secondLargest;