日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

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

發布時間:2023/12/2 java 39 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java获取数组的最小值_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:arr){ //使用加強for循環遍歷

System.out.print(arr[i]+"\t");

}

System.out.println; */

for(int i=0;i

System.out.print(arr[i]+"\t");

}

System.out.println();

}

//獲取最大值

public static int max(int[] arr){

int max=arr[0];

for(int i=0;i

if(arr[i]>max){

max=arr[i];

}

}

return max;

}

//獲取最大值索引

public static int maxIndex(int[] arr){

int maxIndex=0;;

for(int i=0;i

if(arr[i]>arr[maxIndex]){

maxIndex=i;

}

}

return maxIndex;

}

//獲取最小值

public static int min(int[] arr){

int min=arr[0];

for(int i=0;i

if(arr[i]

min=arr[i];

}

}

return min;

}

//獲取最小值索引

public static int minIndex(int[] arr){

int minIndex=0;;

for(int i=0;i

if(arr[i]

minIndex=i;

}

}

return minIndex;

}

//在數組中查找指定元素是否存在 ,如是存在返回true,不存在返回false

public static boolean search(int[] arr,int number){

for(int i=0;i

if(number==arr[i]){

return true;

}

}

return false;

}

//在數組中查找指定元素是否存在 ,如是存在返回索引,不存在返回-1

public static int searchIndex(int[] arr,int number){

for(int i=0;i

if(number==arr[i]){

return i; //返回索引

}

}

return -1;

}

}

效果截圖:

以上就是本文的全部內容,希望對大家的學習有所幫助

您可能感興趣的文章:

總結

以上是生活随笔為你收集整理的java获取数组的最小值_Java 数组获取最大和最小值的实例实现的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。