2017-02-16 11 views
-2

我已决定踏入强大而艰巨的Java世界之旅我来自C++,但是我刚刚开始,我我很快就会赶上我在C++中的位置,但是我偶然发现了一些我似乎无法理解的东西,并且围绕它来包裹我的头。有人能帮助我理解这个逻辑以及它的工作原理吗?感谢您的时间并为我的无知感到遗憾?不了解这些数组是如何为其中的数组添加数值的

基本上,它假设程序保持值的计数并捕获响应数组超出范围的那个。现在我还是很了解它。

package stuPoll; 


public class studentPoll { 

    public static void main(String[] args) { 


     int[] responses = {1, 2, 3, 5, 4, 3, 5, 2, 1, 3, 3, 1, 4, 4, 3, 3, 3, 2, 3, 3, 2, 14}; 

     int[] frequency = new int[9]; 

     for (int anwser = 0; anwser < responses.length; anwser++){ 

      try { 
       ++frequency[responses[anwser]]; 
       System.out.println(responses[anwser]); 
      } 
      catch (ArrayIndexOutOfBoundsException e){ 
       System.out.println(e); 
       System.out.printf("responses[%d] = %d\n\n", anwser, responses[anwser]); 
      } 
      } 

     for (int rating = 1; rating < frequency.length; rating++){ 
      System.out.printf("responses[%d] = %d\n\n", rating, frequency[rating]); 

     } 
     } 

} 

目前,我正在学习有关的异常处理,但是,我穿过这部分代码来

++frequency[responses[anwser]]; 
System.out.println(responses[anwser]); 

我可以看到,它的频率增加[]数组但是当你运行它的代码似乎计算了响应数组中有多少具体的值,并将其计为频率,但它知道确切的下标来计算它,我无法理解它是如何或为什么这样做的?我很遗憾浪费你的时间,但有人可以帮助新手程序员理解这一点吗?我是一个视觉学习者,所以我试图画出它,但我仍然不明白?

+0

代码剪断的作品,因为它如果它被写为'frequency [responses [answers]] = frequency [responses [answer]] + 1' – 2017-02-16 04:50:19

回答

0

ArrayIndexOutOfBounds捕获数组的错误索引访问。 例如:说,如果你的数组的大小为3,并访问ARR [3]那么你得到一个例外,因为你访问一个不可用的指标:

int arr[] = {1,2,3}; 
arr[0] //ok 
arr[1] //ok 
arr[2] //ok 
arr[3] //exception as size is 3 and it does not exist 

的代码片段统计收视率的频率的阵列英寸 (即多少响应具有等级1,有多少等级2等)

频率被存储在频率数组,其中频率[0]对应于响应数目与0的评价中,频率[1]对应于等级为1的响应的数量等等。 所以

++frequency[responses[anwser]]; //increases the count with rating responses[answer](i.e an item in the response array) 
你的情况

现在,当你到达14,你会得到一个indexOutOfBound例外,因为你只从0-9

检查响应希望它可以帮助

+0

那么在这种情况下,响应数组就像是for循环一样吗?例如,当代码开始时,它从频率[0]开始,响应[]然后迭代直到它找到0,然后它增加,否则它移动到频率[1] 2 3等等,直到数组满足一个值那个频率没有覆盖这个界限,并且它捕捉到了这个错误? –

+0

您使用循环来循环响应数组。对于每个响应(A.K.A等级)(即响应[i]),你增加相应的频率阵列指数(即等级数) –

+0

非常感谢@Aditya –