Purpose:
First create an array with a length of 5, then assign a random integer to each bit of the array, and find the smallest (largest) value come out.
Method 1:
int array[] = new int[5]; System.out.println("数组的元素为:"); for (int i=0;i<array.length;i++){ array[i] = (int) (Math.random()*100); System.out.println(array[i]); } System.out.println("----------------------------------------------------"); int min = array[0]; for(int i=1;i<array.length;i++) { if(min>array[i]){ min=array[i]; } } System.out.println("方法二:最小值为:"+min); }
Result:
java quick start)
Method 2:int array[] = new int[5]; System.out.println("数组的元素为:"); for (int i=0;i<array.length;i++){ array[i] = (int) (Math.random()*100); System.out.println(array[i]); } System.out.println("----------------------------------------------------"); //对数组进行排序处理 Arrays.sort(array); System.out.println("方法三:最小值为:"+array[0]); }
##Method 3:
Collections through Collections class .max() and Collections.min() methods to find the maximum and minimum values in an array.
The code is as follows:
Integer array[] = new Integer[5]; System.out.println("数组的元素为:"); for (int i=0;i<array.length;i++){ array[i] = (int) (Math.random()*100); System.out.println(array[i]); } System.out.println("----------------------------------------------------"); //通过 Collections 类的 Collections.max() 和 Collections.min() 方法来查找数组中的最大和最小值: int min = (int)Collections.min(Arrays.asList(array)); int max = (int) Collections.max(Arrays.asList(array)); System.out.println("方法四:最小值为:"+min); System.out.println("方法四:最大值为:"+max);
Result:
## Recommended related video tutorials: java video tutorial
The above is the detailed content of How to implement the minimum value in an array in java. For more information, please follow other related articles on the PHP Chinese website!