【发布时间】:2020-11-20 10:01:28
【问题描述】:
我正在尝试编写一个程序来打印出存储在ArrayList 中的第三大数字。我尝试对其进行排序,然后将列表反转为并使用 get() 方法来获取第三高数字的索引。但它没有考虑前 3 个插槽中是否存在重复。
如何遍历arraylist得到第三个highs值?
到目前为止我做了什么。
import java.util.*;
public class third {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>(); //creating an array object
Scanner scan = new Scanner(System.in); // scanner to read user input
// print statement to get input
System.out.print("Enter any amount of numbers: ");
int i = 0;
while (scan.hasNextInt()) {// while there is an hasnext has an int
numbers.add(scan.nextInt()); //adding input(numbers) to an arraylist
i++; //increment by 1
}
scan.close(); // close the scanner if the user doesnt enter a number.
System.out.println("you entered: " + numbers);
System.out.println("The largest number you entered is: " + Collections.max(numbers));//print largest number
System.out.println("The smallest number you entered is: " + Collections.min(numbers));//print smallest number
Collections.sort(numbers); //sorting the numbers from lowest to highest
System.out.println("Sorted: " + numbers); //print sorted numbers
Collections.reverse(numbers); //reverse the order to use to get the third highest value
System.out.println("Highest to lowest: " + numbers);
System.out.println("Third highest number is:" + numbers.get(2));//get the third index of the sorted ArrayList
}
}
【问题讨论】:
-
使用Set 代替
ArrayList? -
循环 3 次会产生比你写的更简单有效的方法。