如何在java中从数组打印多个最大值
我刚刚开始用java编程,我正在尝试一些东西。我已经编写了一些代码来创建我自己的带有x索引的数组,我可以在程序运行时填充这些索引。因此,如果我运行这个程序,我可以说x=5,我将有5个索引需要填写,例如5,2,7,4和7。然后程序将找到最大值并打印它。然后我想知道是否可以让我的程序打印maxValue在数组中的次数。在上面的例子中是两个。但我似乎不知道该怎么做 这是我目前掌握的代码:如何在java中从数组打印多个最大值,java,arrays,max,Java,Arrays,Max,我刚刚开始用java编程,我正在尝试一些东西。我已经编写了一些代码来创建我自己的带有x索引的数组,我可以在程序运行时填充这些索引。因此,如果我运行这个程序,我可以说x=5,我将有5个索引需要填写,例如5,2,7,4和7。然后程序将找到最大值并打印它。然后我想知道是否可以让我的程序打印maxValue在数组中的次数。在上面的例子中是两个。但我似乎不知道该怎么做 这是我目前掌握的代码: import java.util.*; public class oefeningen { static vo
import java.util.*;
public class oefeningen {
static void maxValue(int[] newArray){//this method decides the largest number in the array
int result = newArray[0];
for (int i=1; i<newArray.length; i++){
if (newArray[i] > result){
result = newArray[i];
}
}
System.out.println("The largest number is: " +result);
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int x; //this is the main part of the array
System.out.println("Please enter size of array:");
x = keyboard.nextInt();
int[] newArray = new int[x];
for (int j=1; j<=x; j++){//this bit is used for manually entering numbers in the array
System.out.println("Please enter next value:");
newArray[j-1] = keyboard.nextInt();
}
maxValue(newArray);
}
}
只需传递数组和任意值即可计算它在数组中出现的次数
public int checkAmountOfValuesInArray(int[] array, int val) {
int count = 0;
for (int i = 0; i < array.length; i++) {
if (array[i]==val) count++;
}
return count;
}
或者,如果您想在一个循环中完成所有操作:
static void maxValue(int[] newArray) {//this method decides the largest number in the array
int result = newArray[0];
int count = 1;
for (int i = 1; i < newArray.length; i++) {
if (newArray[i] > result) {
result = newArray[i];
count = 1;
} else if (newArray[i] == result) {
count++;
}
}
System.out.println("The largest number is: " + result+ ", repeated: " + count + " times");
}
您可以跟踪maxValue函数,并在每次发现新的最大值时重置计数器。大概是这样的:
static void maxValue(int[] newArray){//this method decides the largest number in the array
int count = 0;
int result = newArray[0];
for (int i=1; i<newArray.length; i++){
if (newArray[i] > result){
result = newArray[i];
// reset the count
count = 1;
}
// Check for a value equal to the current max
else if (newArray[i] == result) {
// increment the count when you find another match of the current max
count++;
}
}
System.out.println("The largest number is: " +result);
System.out.println("The largest number appears " + count + " times in the array");
}
添加一个计数器变量,当newArray[i]==result时添加该变量,当您将结果更改为其他内容时将其重置为1。添加一个计数器,并在每次发现等于当前最大值的元素时将其递增。当当前最大值更改时,将其重置为1。你应该能自己弄明白,不知道这是不是另一个问题的重复。。。似乎这个问题是问我如何计算等于最大值的项目数链接问题与计算元素无关。。。