【问题标题】:How to find the index of the largest and smallest value in an array?如何找到数组中最大值和最小值的索引?
【发布时间】: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)。

标签: java arrays methods


【解决方案1】:

这将提示您输入数组,然后 System.out.println 最小值和最大值。

我刚刚修改了这个链接的代码:

https://www.sanfoundry.com/java-program-find-largest-number-array/

import java.util.Scanner;
public class Largest_Smallest {
     public static void main(String[] args) 
        {
            int n, max, min;
            Scanner s = new Scanner(System.in);
            System.out.print("Enter number of elements in the array:");
            n = s.nextInt();
            int a[] = new int[n];
            System.out.println("Enter elements of array:");
            for(int i = 0; i < n; i++)
            {
                a[i] = s.nextInt();
            }
            max = a[0];

            for(int i = 0; i < n; i++){
                if(max < a[i])
                {
                    max = a[i];
                }
            }
            min = max;
            for(int i = 0; i < n; i++){
                if(min > a[i])
                {
                    min = a[i];
                }
            }
            System.out.println("Maximum value:"+max);
            System.out.println("Maximum value:"+min);
        }


  }

【讨论】:

    猜你喜欢
    • 2013-01-11
    • 2018-10-22
    • 2021-04-28
    • 2018-04-25
    • 2016-08-21
    • 2014-05-19
    • 1970-01-01
    • 2021-02-10
    • 1970-01-01
    相关资源
    最近更新 更多