数组和增强的for循环? [英] Arrays and enhanced for loops?

查看:86
本文介绍了数组和增强的for循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释一下这种方法发生了什么吗?

Can someone please explain what is going on in this method?

class test{  
public static void main(String args[])
{
   int[] x = new int[4]; 
   int[] xy = new int[4]; 
  //System.out.println(xy[0]); 
    for(int j : x) { 
       xy[j] += 1;
    }
   System.out.println(xy[0]); }}

所以我认为增强的for循环可以做到这一点

So I thought that the enhanced for loop would be doing this

/**for(int j=0; j < x.length(); j++)
xy[j=0] = 1
xy[j=1]=1
xy[j=2]=1
xy[j=3]=1*/

但是从我一直在阅读的内容来看,增强的for循环正在执行for(int element:array).仍然,我不明白我的方法中的for循环实际上在做什么.我已经尝试过System.out.println()语句来检查被放入数组xy中的内容,但是它要么是地址,要么是0.

but from what I've been reading, the enhanced for loop is doing for(int element:array). Still, I don't understand what the for loop in my method is actually doing. I have tried System.out.println() statements to check what was being put into the array xy, but it is either addresses or 0.

感谢所有帮助,如果感到困惑,我们深表歉意.

Thanks for all the help and apologizes if this is confusing.

推荐答案

对于您在此处使用的每个循环都会为j分配一个已经分配给数组x的值(在您的情况下为0).

For Each loop that you have used in here does assign j a value that is already assigned to array x (which in your case is 0 ).

根据您的x和xy数组的情况:-

As according to your case of x and xy array:-

x[0]=0;    xy[0]=0
x[1]=0;    xy[0]=0
x[2]=0;    xy[0]=0
x[3]=0;    xy[0]=0

根据您的程序情况描述每个循环:-

Describing for each loop according to your program case:-

for(j : x)

  1. 这意味着它将运行4次,这是数组x的长度.

  1. This implies it will run for 4 times which is the length of your array x.

首次运行时,将发生以下过​​程

when running first time the following process will happen

j=x[0] (so j=0 coz x[0] according to your case)
xy[0]=xy[0]+1 (so now xy[0] value becomes 1)

  • 类似地 对于每个的第二次

  • Similarly for the second run of for each

    j=x[1] (so j=0 coz x[0] according to your case)
    xy[0]=xy[0]+1 (so now xy[0] value becomes 2 as in previous for each run xy[0]=1)
    

  • 因此,总的来说,每个循环的第4次运行结束时,您都会拥有xy[0]=4.

    最后,打印语句将打印4.

    Finally the print statement will print 4.

    这篇关于数组和增强的for循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆