gpt4 book ai didi

java - 计算数组中整数的出现次数

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:48:17 24 4
gpt4 key购买 nike

<分区>

我正在编写一个程序来计算输入到数组中的整数的出现次数,例如,如果您输入 1 1 1 1 2 1 3 5 2 3,该程序将打印出不同的数字及其出现次数,如下所示:

1 出现 5 次,2 出现 2 次,3出现2次,5 出现 1 次

它几乎完成了,除了一个我想不通的问题:

import java.util.Scanner;
import java.util.Arrays;
public class CountOccurrences
{
public static void main (String [] args)
{

Scanner scan = new Scanner (System.in);

final int MAX_NUM = 10;

final int MAX_VALUE = 100;

int [] numList;

int num;

int numCount;

int [] occurrences;

int count[];

String end;

numList = new int [MAX_NUM];

occurrences = new int [MAX_NUM];

count = new int [MAX_NUM];

do
{
System.out.print ("Enter 10 integers between 1 and 100: ");

for (num = 0; num < MAX_NUM; num++)
{
numList[num] = scan.nextInt();
}

Arrays.sort(numList);

count = occurrences (numList);

System.out.println();

for (num = 0; num < MAX_NUM; num++)
{
if (num == 0)
{
if (count[num] <= 1)
System.out.println (numList[num] + " occurs " + count[num] + " time");

if (count[num] > 1)
System.out.println (numList[num] + " occurs " + count[num] + " times");
}

if (num > 0 && numList[num] != numList[num - 1])
{
if (count[num] <= 1)
System.out.println (numList[num] + " occurs " + count[num] + " time");

if (count[num] > 1)
System.out.println (numList[num] + " occurs " + count[num] + " times");
}
}

System.out.print ("\nContinue? <y/n> ");
end = scan.next();

} while (!end.equalsIgnoreCase("n"));
}


public static int [] occurrences (int [] list)
{
final int MAX_VALUE = 100;

int num;

int [] countNum = new int [MAX_VALUE];

int [] counts = new int [MAX_VALUE];

for (num = 0; num < list.length; num++)
{
counts[num] = countNum[list[num]] += 1;
}

return counts;
}
}

我遇到的问题是,无论“num”的当前值是多少,“count”只打印出 1,问题不在于计算出现次数的方法,因为当您输入数字时在变量的位置,值发生变化。

有什么方法可以改变它以便正确打印出出现的事件,或者我应该尝试其他方法吗?解决方案越简单越好,因为我还没有超越一维数组。

感谢您的帮助!

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