Java语言怎么求出一个数组里的最大数,如果最大数有多个,要求输出多个最大数,请问怎么输出多个最大数呢
这个很简单啊,可以看下一以下代码,直接可以使用了
```java
public class Main {
public static void main(String[] args) {
int[] array = {1, 2, 3, 2, 4, 5, 2, 6, 7, 2}; // 示例数组
int maxCount = 0; // 最大数出现的次数
int max = Integer.MIN_VALUE; // 当前最大数
for (int i = 0; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
maxCount = 1;
} else if (array[i] == max) {
maxCount++;
}
}
System.out.println("最大数是:" + max);
System.out.println("最大数出现的次数是:" + maxCount);
}
}
```
【以下回答由 GPT 生成】
首先,我们可以通过以下步骤找出一个给定数组中的所有最大值并输出:
下面是一个示例代码:
import java.util.ArrayList;
public class FindMaxValues {
public static void main(String[] args) {
int[] array = {5, 10, 15, 20, 15, 20, 25};
ArrayList<Integer> maxValues = new ArrayList<Integer>();
int max = Integer.MIN_VALUE;
//找出数组中的最大值
for (int i = 0; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
//将最大值添加到ArrayList中
maxValues.add(max);
//找出与最大值相等的元素并添加到ArrayList中
for (int i = 0; i < array.length; i++) {
if (array[i] == max && array[i] != maxValues.get(0)) {
maxValues.add(array[i]);
}
}
//输出最大值
for (int i = 0; i < maxValues.size(); i++) {
System.out.println("最大值: " + maxValues.get(i));
}
}
}
这样,我们就可以找出给定数组中的所有最大值并输出了。
【相关推荐】