gpt4 book ai didi

java - 如何查找最小值和最大值以及每个值出现的次数

转载 作者:行者123 更新时间:2023-12-01 23:09:42 27 4
gpt4 key购买 nike

我在解决这个作业问题时遇到了困难。该问题要求我创建一个程序来读取用户输入的数字并获取这些数字的最小值和最大值。

基本上,输出应如下所示:

输入数量:10

输入以空格分隔的 10 个数字,然后按 Enter:1 2 3 1 2 3 4 5 6 3

最小值为 1,出现 2 次

最大值为 6,出现 1 次

我能够创建方法来获取最小值和最大值。我不知道如何用我所拥有的来获得最小和最大出现的次数。我也不知道如何让扫描仪读取同一行上的整数输入。

import java.util.Scanner;

public class homework2
{
public int min(int[] array)
{
int min = array[0];
for (int i = 0; i < array.length; i++)
{
if (array[i] < min)
{
min = array[i];
}
}
return min;
}

public int max(int[] array)
{
int max = 0;
for (int i = 0; i < array.length; i++)
{
if (array[i] > max)
{
max = array[i];
}
}
return max;
}

public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Enter the length of the array:");
int length = s.nextInt();
int[] myArray = new int[length];
System.out.println("Enter the elements of the array:");

for (int i = 0; i < length; i++)
{
myArray[i] = s.nextInt();
}
}
}

最佳答案

这是一个简单的程序来完成您的需要:

public static void main(String[] args) {
int[] array = {1, 2, 3, 1, 2, 3, 4, 5, 6, 3}; // get your actual array
int first = array[0];

// initial values
int min = first;
int minOccurs = 1;
int max = first;
int maxOccurs = 1;

for(int i = 1; i < array.length; i++) {
int current = array[i];
if(current == min) {
minOccurs++;
} else if (current < min) {
min = current;
minOccurs = 1;
}

if(current == max) {
maxOccurs++;
} else if (current > max) {
max = current;
maxOccurs = 1;
}
}

System.out.println("Min is " + min + " and has " + minOccurs + " occurrences");
System.out.println("Max is " + max + " and has " + maxOccurs + " occurrences");
// prints: "Min is 1 and has 2 occurrences"
// prints: "Max is 6 and has 1 occurrences"
}

关于java - 如何查找最小值和最大值以及每个值出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58381857/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com