【发布时间】:2015-11-01 04:46:47
【问题描述】:
我正在编写一个程序来计算输入到数组中的整数的出现次数,例如,如果你输入 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,而问题不在于计算出现次数的方法,因为当您输入数字时在变量的位置,值会发生变化。
有什么方法可以改变它,以便正确打印出出现的情况,或者我应该尝试其他方法吗? 而且解决方案越简单越好,因为我还没有超越一维数组。
感谢您的帮助!
【问题讨论】:
-
请以此为契机学习调试。所有 IDE(eclipse、Netbeans、IntellIJ、..)都带有简洁的调试工具。
-
问题出在你的出现函数中。
counts[num] = countNum[list[num]] += 1;行没有做你认为它正在做的事情。它在数组中移动,将数字的计数放在单独的索引中。以您当前的输入为例,counts数组的值为[1, 2, 3, 4, 5, 1, 2, 1, 2, 1, ... 0]。第一个[1, 2, 3, 4, 5是因为你的数组中有5 个1,下一个1, 2是因为你的数组中有2 个2,等等。你需要重写你的occurrences函数。会留下这个作为答案,但问题已关闭。