【发布时间】:2015-06-18 05:35:01
【问题描述】:
按照建议,我回去了,开始查看几个月前我错误的一些代码,并一直在尝试更新它,以提高效率。
我想要的只是让我的方法返回一个包含出现次数的新数组。
例如:count({2,4,0,7,4,2,1,0})returns {2,1,2,0,2,0,0,1}
到目前为止,我的方法是这样的,只是为了记录,我想观众的缘故,我正在使用的数组是这样的。
18 29 23 35 23 28 36 27 16 21 33 21 18 33 16 6 19 22 9 26 28 16 19 14 18 12 17 28
这是我的计数课
public int[] count(Integer[] nums)
{
Integer[] numOccur = new Integer[nums.length]; //new array that will be returned with the occurances
for (int i = 0; i < nums.length; ++i) //goes through the array for nums.length times.
{
Integer count = nums[i]; //assigns count to nums[i]
numOccur[count]++; //ERROR
System.out.println(numOccur[i]); //testing to see if i'm printing the right value
}
return numOccur;
}
我收到了
at WeatherSrv.count(WeatherSrv.java:94)
at WeatherDrv.main(WeatherDrv.java:55)
Java Result: 1
我知道问题发生在我分配数组[] numOccur 中的新元素时,仅仅是因为我的分配吗?我只是想知道我是否朝着正确的方向前进。
在我之前的版本中,我只使用 switch 语句,没有数组,所以这有点不同。
编辑 1:我应该发布我正在使用的主要方法!
weather.count(res) 其中 res 是我在班级上方发布的数组
/*这是我的第一篇文章 - 如果有人对措辞更好的问题有任何建议,请不要犹豫,我想要最清楚的,没有给出的答案
【问题讨论】:
-
也许你只需要转换 count 我的意思是你应该这样做:numOccur[ (int)count ]++;
-
这是因为它是一个整数,我需要它作为一个整数吗?无论如何,我仍然遇到与以前相同的错误
-
应该是
count( new int [] {2,4,0,7,4,2,1,0} ),因为方法count接受int的数组作为参数 -
我已经给它传递了一个数组,不需要在方法中初始化一个新的
-
使用
HashMap会更适合这个。