我刚开始用java编程,我正在尝试一些东西。我编写了一些代码来创建我自己的x索引数组,我可以在程序运行时填写这些代码。因此,如果我运行该程序,我可以说x = 5,我将有5个索引填写(例如5,2,7,4和7)。然后程序将找到最大值并打印出来。然后我想知道我是否可以让我的程序打印我的maxValue在数组中的次数。在上面的例子中,它将是两个。我似乎无法找到如何做到这一点。
这是我到目前为止的代码:
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);
}
}
答案 0 :(得分:1)
您可以在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");
}
答案 1 :(得分:0)
只需传递数组和任何值来计算它在数组中出现的次数
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");
}