栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java 数组获取最大和最小值的实例实现

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java 数组获取最大和最小值的实例实现

以下实例演示了如何通过 Collections 类的 Collections.max() 和 Collections.min() 方法来查找数组中的最大和最小值:

Main.java 文件:

import java.util.Arrays;
import java.util.Collections;
 
public class Main {
  public static void main(String[] args) {
    Integer[] numbers = { 8, 2, 7, 1, 4, 9, 5};
    int min = (int) Collections.min(Arrays.asList(numbers));
    int max = (int) Collections.max(Arrays.asList(numbers));
    System.out.println("最小值: " + min);
    System.out.println("最大值: " + max);
  }
}

以上代码运行输出结果为:

最小值: 1
最大值: 9

java求数组中元素最大值最小值及其下标

功能需求:遍历数组,并求出数组中元素的最大元素,最小元素,及其相应的索引等问题,要求用方法完成.
思路:分别创建不同的方法,然后再调用方法.

代码展示:

public class Array{
  public static void main(String[] args){
    int[] arr={13,45,7,3,9,468,4589,76,4}; //声明数组并赋值
    //调用遍历的方法
    print(arr); //在同一个类中,类名可以省略

    //调用获取最大值的方法
    System.out.println("最大元素为:"+max(arr));

    //调用获取最大值索引的方法
    System.out.println("最大元素的索引为:"+maxIndex(arr));

    //调用获取最小值的方法
    System.out.println("最小元素为:"+min(arr));

    //调用获取最小值索引的方法
    System.out.println("最小元素的索引为:"+minIndex(arr));

    //调用查找元素是否存在的方法
    System.out.println("查找元素的状态为:"+search(arr,9));

    //调用查找元素是否存在并返回索引方法
    System.out.println("查找元素的索引为:"+searchIndex(arr,9));

  }



  //遍历数组
  public static void print(int[] arr){
    
    for(int i=0;imax){
 max=arr[i];
      }
    }
    return max;
  }

  //获取最大值索引
  public static int maxIndex(int[] arr){
    int maxIndex=0;; 
    for(int i=0;iarr[maxIndex]){
 maxIndex=i;
      }
    }
    return maxIndex;
  }

  //获取最小值
  public static int min(int[] arr){
    int min=arr[0]; 
    for(int i=0;i

效果截图:

 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/136887.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号