我正在编写一个程序来计算输入到数组中的整数的出现次数,例如,如果你输入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;
}
}
我遇到的问题是,无论“数字”的当前值是多少。是,&#39;计数&#39;只打印出1,问题不在计算出现次数的方法中,因为当你在变量的位置输入数字时,值就会改变。
有什么方法可以改变它,以便它能正确地打印出事件,或者我应该尝试别的吗? 而且解决方案越简单越好,因为我还没有超越单维数组。
感谢您的帮助!
答案 0 :(得分:3)
尝试HashMap。对于这种类型的问题,哈希非常有效且快速。
我编写了这个函数,它接受数组并返回一个HashMap,其键是数字,值是该数字的出现。
public static HashMap<Integer, Integer> getRepetitions(int[] testCases) {
HashMap<Integer, Integer> numberAppearance = new HashMap<Integer, Integer>();
for(int n: testCases) {
if(numberAppearance.containsKey(n)) {
int counter = numberAppearance.get(n);
counter = counter+1;
numberAppearance.put(n, counter);
} else {
numberAppearance.put(n, 1);
}
}
return numberAppearance;
}
现在迭代遍历hashmap并打印出这样的数字:
HashMap<Integer, Integer> table = getRepetitions(testCases);
for (int key: table.keySet()) {
System.out.println(key + " occur " + table.get(key) + " times");
}
输出:
答案 1 :(得分:2)
我会使用一个Bag,这个集合可以计算项目在集合中出现的次数。 Apache Commons有一个实现它。这是他们的interface,这里是sorted tree implementation。
你会做这样的事情:
Bag<Integer> bag = new TreeBag<Integer>();
for (int i = 0; i < numList.length; i++) {
bag.add(numList[i]);
}
for (int uniqueNumber: bag.uniqueSet()) {
System.out.println("Number " + uniqueNumber + " counted " + bag.getCount(uniqueNumber) + " times");
}
上面的示例从您的numList
数组中获取元素,并将它们添加到Bag
以生成计数,但是您甚至不需要数组。只需将元素直接添加到Bag
即可。类似的东西:
// Make your bag.
Bag<Integer> bag = new TreeBag<Integer>();
...
// Populate your bag.
for (num = 0; num < MAX_NUM; num++) {
bag.add(scan.nextInt());
}
...
// Print the counts for each unique item in your bag.
for (int uniqueNumber: bag.uniqueSet()) {
System.out.println("Number " + uniqueNumber + " counted " + bag.getCount(uniqueNumber) + " times");
}
答案 2 :(得分:1)
您可以从初始化MIN和MAX之间的值数组开始。然后,当该值出现 1 时,您可以添加到数组的每个元素。像,
Scanner scan = new Scanner(System.in);
final int MAX_NUM = 10;
final int MAX_VALUE = 100;
final int MIN_VALUE = 1;
final int SIZE = MAX_VALUE - MIN_VALUE;
int[] numList = new int[SIZE];
System.out.printf("Enter %d integers between %d and %d:%n",
MAX_NUM, MIN_VALUE, MAX_VALUE);
for (int i = 0; i < MAX_NUM; i++) {
System.out.printf("Please enter number %d: ", i + 1);
System.out.flush();
if (!scan.hasNextInt()) {
System.out.printf("%s is not an int%n", scan.nextLine());
i--;
continue;
}
int v = scan.nextInt();
if (v < MIN_VALUE || v > MAX_VALUE) {
System.out.printf("%d is not between %d and %d%n",
v, MIN_VALUE, MAX_VALUE);
continue;
}
numList[v - MIN_VALUE]++;
}
boolean first = true;
for (int i = 0; i < SIZE; i++) {
if (numList[i] > 0) {
if (!first) {
System.out.print(", ");
} else {
first = false;
}
if (numList[i] > 1) {
System.out.printf("%d occurs %d times",
i + MIN_VALUE, numList[i]);
} else {
System.out.printf("%d occurs once", i + MIN_VALUE);
}
}
}
System.out.println();
1 另见 radix sort counting sort。
答案 3 :(得分:1)
我要说的是,我花了一些时间来弄清楚.get()
和count
这两个变量代表什么,可能需要一些评论。但最后我发现了这个错误。
假设输入十个数字为:countNum
排序后,5, 6, 7, 8, 5, 6, 7, 8, 5, 6
为:numList
5, 5, 5, 6, 6, 6, 7, 7, 8, 8
返回的数组count
应为:occurrences()
实际上,此结果数组中唯一有用的数字是:
[1, 2, 3, 1, 2, 3, 1, 2, 1, 2]
其他数字,例如count[2]: 3 count number for numList[2]: 5
count[5]: 3 count number for numList[5]: 6
count[7]: 2 count number for numList[7]: 7
count[9]: 2 count number for numList[9]: 8
之前的前两个数字1, 2
,仅用于逐步计算总和,对吧?因此,您的循环逻辑应更改如下:
删除第一个3
代码块:
if
将第二个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
在此之后,您的代码应该按预期运行良好。
顺便说一下,你真的不需要如此错综复杂地去做。试试if ((num + 1) == MAX_NUM || numList[num] != numList[num + 1]) {
......
}
:)
答案 4 :(得分:0)
如果您使用这种方法,我认为您可以大大简化您的代码。您仍需修改以包含MAX_NUM
和MAX_VALUE
。
public static void main(String[] args) {
Integer[] array = {1,2,0,3,4,5,6,6,7,8};
Stack stack = new Stack();
Arrays.sort(array, Collections.reverseOrder());
for(int i : array){
stack.push(i);
}
int currentNumber = Integer.parseInt(stack.pop().toString()) , count = 1;
try {
while (stack.size() >= 0) {
if (currentNumber != Integer.parseInt(stack.peek().toString())) {
System.out.printf("%d occurs %d times, ", currentNumber, count);
currentNumber = Integer.parseInt(stack.pop().toString());
count = 1;
} else {
currentNumber = Integer.parseInt(stack.pop().toString());
count++;
}
}
} catch (EmptyStackException e) {
System.out.printf("%d occurs %d times.", currentNumber, count);
}
}