How to find the maximum value in an array using Java?
To find the maximum value of an array in Java, you can use a loop to compare each element in the array. Start by assuming the first element in the array is the maximum, and then iterate through to find the actual maximum value. Here is an example:
public class Main {
public static void main(String[] args) {
int[] array = {5, 2, 9, 1, 7};
int max = array[0]; // 假设第一个元素为最大值
for (int i = 1; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
System.out.println("最大值为: " + max);
}
}
In the example above, we defined an array containing integers, then used a for loop to iterate through each element in the array. During each iteration, an if statement is used to compare the current element with the max value, and if the current element is greater than the max, the value of max is updated. In the end, the value of max will be the maximum value in the array.