【发布时间】:2019-08-21 11:15:00
【问题描述】:
我正在尝试制作将数字带入数组的方法,但我一直坚持如何将最大/最小值的索引“作为数组”返回。
public static void main(String[] args) {
array();
int max[];
}
public static void array() {
Scanner input = new Scanner(System.in);
System.out.println("Length of the Array");
int x = input.nextInt();
int array[] = new int[x];
System.out.println("chose the numbers");
for (int i = 0; i < x; i++) {
array[i] = input.nextInt();
}
}
public static int max(int[] array) {
int max = 0;
int index = -1;
for (int i = 0; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
index = i;
}
{
return index;
第一部分处理数组中的长度和数字,但返回最大小值的索引作为数组。我不确定如何继续。
【问题讨论】:
-
stackoverflow.com/questions/18525474/… 或 stackoverflow.com/questions/18525474/… 的可能重复项。这个问题之前已经问过很多次了,google "java index of max and min value in array site:stackoverflow.com"
-
如果性能在这里不是什么大问题,您可以使用两行代码获取最大值和最小值:
int max = Arrays.asList(array).stream().max(Integer::compare); int min = Arrays.asList(array).stream().min(Integer::compare); -
我想将最大和最小的 1.(index) 返回为 2.(array)。