gpt4 book ai didi

java - java 中的错误 - 查找 ArrayList 中的最大值

转载 作者:行者123 更新时间:2023-12-02 07:50:47 32 4
gpt4 key购买 nike

以下是我为回答该问题而编写的程序 -

“现在使用 ArrayList 和 Integer 包装类来存储值,并通过使用 Scanner 类从控制台读取输入来初始化元素。扩展程序以识别 ArrayList 中的 n 个最大值。”

import java.util.ArrayList;
import java.util.Scanner;

public class ArraylistInput {
/**
* @param args
*/
public static void main(String[] args) {

ArrayList<Integer> val = new ArrayList<Integer>();
Scanner in = new Scanner(System.in);
System.out.println("Enter the length of you Array List ");
int nos = in.nextInt();
// Recorrd the input numbers
for (int i = 0 ; i < nos; i++)
{
System.out.println("Enter values for the ArrayList ");
int Input = in.nextInt();
val.add(Input);
}

// Display the arraylist
for (int j = 0; j < nos; j++)
{
int x = val.get(j);
System.out.println("Index " + (j+1) + ": " + x);
}
System.out.println("How meny maximmum values do you want? ");
int max =0; // initial max value
int nmax = in.nextInt(); // number of maximum values
int length = val.size(); // size of the arraylist

// finding the maximum values in ascending order without sorting
for (int h = 1; h <= nmax ; h++)
{
for (int k=0;k < length; k++)
{
if (val.get (k) > max)
{
max = val.get(k);
}
}
System.out.println ("maximmum = " + max);
int z = val.indexOf(max); // removing the higest value after printing
val.remove(z);
}
}
}

Output and Error:

Enter the length of you Array List

3

Enter values for the ArrayList

12

Enter values for the ArrayList

45

Enter values for the ArrayList

8

Index 1: 12 Index 2: 45 Index 3: 8

How meny maximmum values do you want?

2

maximmum = 45

Exception in thread "main" maximmum = 45 java.lang.ArrayIndexOutOfBoundsException: -1 at java.util.ArrayList.elementData(Unknown Source) at java.util.ArrayList.remove(Unknown Source) at ArraylistInput.main(ArraylistInput.java:46)

最佳答案

我会执行以下操作:

Collections.sort(myList, Collections.reverseOrder());
List<Integer> maxn = myList.subList(0, n);
System.out.printf("The maximum %d values are: %s%n", n, maxn);
maxn.clear(); //This clears the sublist and removes its elements from the source list

这将为您提供一个列表,其中包含列表中最多 n 个元素。

关于java - java 中的错误 - 查找 ArrayList 中的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10259666/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com