public class ArrayStudentPoll {
public static void main( String args[] )
{
// array of survey responses
int responses[] = { 1, 2, 6, 4, 8, 5, 9, 7, 8, 10, 1, 6, 3, 8, 6,
10, 3, 8, 2, 7, 6, 5, 7, 6, 8, 6, 7, 5, 6, 6, 5, 6, 7, 5, 6,
4, 8, 6, 8, 10 };
int frequency[] = new int[ 11 ]; // array of frequency counters
// for each answer, select responses element and use that value
// as frequency index to determine element to increment
for ( int answer = 0; answer < responses.length; answer++ )
++frequency[ responses[ answer ] ];
System.out.printf( "%s%10s\n", "Rating", "Frequency" );
// output each array element's value
for ( int rating = 1; rating < frequency.length; rating++ )
System.out.printf( "%6d%10d\n", rating, frequency[ rating ] );
}
}
这是我在项目中查看的代码。
我了解的所有内容,但
++frequency[i];
部分中的频率是数组而不是数字?它在那里到底在做什么?他们写了评论,但我还是没收到。这是我要摆脱的结果
Rating Frequency
1 2
2 2
3 2
4 2
5 5
6 11
7 5
8 7
9 1
10 3
最佳答案
++frequency[responses[answer]]
预增加responses[answer]
数组的第frequency
个元素。
相当于
frequency[responses[answer]] = frequency[responses[answer]] + 1;
顺便说一句,使用后递增(
frequency[responses[answer]]++
)在此程序中将得到相同的结果,因为此代码未使用增量运算符的返回值。关于java - 预递增数组对象(++ frequency [i];)是什么意思?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34894179/