以下程序应该要求用户输入整数,将它们存储在ArrayList中,询问顺序(即他们是否想要最高数字,第二高,第三高等等)并显示它:
import java.util.*;
public class Order
{
public static int highestByOrder(int n, ArrayList<Integer> list)
{
int nth_highest=0;
for (int i=0; i<n; i++)
{
nth_highest=0;
int index=0;
for (int el:list)
{
if (el>nth_highest)
{
nth_highest=el;
index++;
}
}
if (n==1)
break;
else
list.remove(index);
}
return nth_highest;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<Integer>();
System.out.println("How many elements do you want to enter? ");
int n = sc.nextInt();
System.out.println("Enter the elements: ");
for (int i = 0; i<n; i++)
{
list.add(sc.nextInt());
}
System.out.println("Enter the order: ");
int order=sc.nextInt();
System.out.println("The highest element by order " + order + " is "
+ highestByOrder(order, list));
}
}
运行它时会得到'IndexOutOfBoundsException'。我的程序中找不到任何错误。请帮忙!
这是完整的错误:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 5, Size: 5
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.remove(Unknown Source)
at Order.highestByOrder(Order.java:25) at Order.main(Order.java:43)
答案 0 :(得分:0)
无法添加评论,因此将评论发布为答案
我尝试了你的程序,它正在为我工作
您想输入多少个元素? 4 输入元素: 7 2 9 3 输入订单: 2 2阶的最高元素是7
你可以告诉我你在尝试什么价值?/