What is the method in Java to find the maximum and minimum values?

In Java, you can use the following methods to find the maximum and minimum values:

  1. Find the maximum value:
  2. Array nums holds integers, and we find the maximum value within the array by using the Arrays.stream() method. This maximum value is then printed out as a message.
  3. Find the minimum value:
  4. Create an array called nums with values 3, 6, 2, 8, and 4. Find the minimum value in the array and print it out along with the message “The minimum value is:”.

Alternatively, the maximum and minimum values can also be found by iterating through the array, as demonstrated below:

int[] nums = {3, 6, 2, 8, 4};
int max = nums[0];
int min = nums[0];

for (int i = 1; i < nums.length; i++) {
    if (nums[i] > max) {
        max = nums[i];
    }
    if (nums[i] < min) {
        min = nums[i];
    }
}

System.out.println("最大值为:" + max);
System.out.println("最小值为:" + min);
Leave a Reply 0

Your email address will not be published. Required fields are marked *